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,
147                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
148                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
149                  gpu_prog *Prog)
150       : IslNodeBuilder(Builder, Annotator, 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   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
1087   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
1088   Instruction *Parameters = new AllocaInst(
1089       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
1090 
1091   int Index = 0;
1092   for (long i = 0; i < Prog->n_array; i++) {
1093     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1094       continue;
1095 
1096     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1097     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1098 
1099     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
1100     DevArray = createCallGetDevicePtr(DevArray);
1101 
1102     Value *Offset = getArrayOffset(&Prog->array[i]);
1103 
1104     if (Offset) {
1105       DevArray = Builder.CreatePointerCast(
1106           DevArray, SAI->getElementType()->getPointerTo());
1107       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1108       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1109     }
1110     Value *Slot = Builder.CreateGEP(
1111         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1112 
1113     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1114       Value *ValPtr = BlockGen.getOrCreateAlloca(SAI);
1115       Value *ValPtrCast =
1116           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1117       Builder.CreateStore(ValPtrCast, Slot);
1118     } else {
1119       Instruction *Param =
1120           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
1121                          Launch + "_param_" + std::to_string(Index),
1122                          EntryBlock->getTerminator());
1123       Builder.CreateStore(DevArray, Param);
1124       Value *ParamTyped =
1125           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1126       Builder.CreateStore(ParamTyped, Slot);
1127     }
1128     Index++;
1129   }
1130 
1131   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1132 
1133   for (long i = 0; i < NumHostIters; i++) {
1134     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1135     Value *Val = IDToValue[Id];
1136     isl_id_free(Id);
1137     Instruction *Param =
1138         new AllocaInst(Val->getType(), AddressSpace,
1139                        Launch + "_param_" + std::to_string(Index),
1140                        EntryBlock->getTerminator());
1141     Builder.CreateStore(Val, Param);
1142     Value *Slot = Builder.CreateGEP(
1143         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1144     Value *ParamTyped =
1145         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1146     Builder.CreateStore(ParamTyped, Slot);
1147     Index++;
1148   }
1149 
1150   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1151 
1152   for (long i = 0; i < NumVars; i++) {
1153     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1154     Value *Val = IDToValue[Id];
1155     isl_id_free(Id);
1156     Instruction *Param =
1157         new AllocaInst(Val->getType(), AddressSpace,
1158                        Launch + "_param_" + std::to_string(Index),
1159                        EntryBlock->getTerminator());
1160     Builder.CreateStore(Val, Param);
1161     Value *Slot = Builder.CreateGEP(
1162         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1163     Value *ParamTyped =
1164         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1165     Builder.CreateStore(ParamTyped, Slot);
1166     Index++;
1167   }
1168 
1169   for (auto Val : SubtreeValues) {
1170     Instruction *Param =
1171         new AllocaInst(Val->getType(), AddressSpace,
1172                        Launch + "_param_" + std::to_string(Index),
1173                        EntryBlock->getTerminator());
1174     Builder.CreateStore(Val, Param);
1175     Value *Slot = Builder.CreateGEP(
1176         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1177     Value *ParamTyped =
1178         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1179     Builder.CreateStore(ParamTyped, Slot);
1180     Index++;
1181   }
1182 
1183   auto Location = EntryBlock->getTerminator();
1184   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1185                          Launch + "_params_i8ptr", Location);
1186 }
1187 
1188 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1189   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1190   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1191   isl_id_free(Id);
1192   isl_ast_node_free(KernelStmt);
1193 
1194   if (Kernel->n_grid > 1)
1195     DeepestParallel =
1196         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1197   else
1198     DeepestSequential =
1199         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1200 
1201   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1202   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1203 
1204   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1205 
1206   assert(Kernel->tree && "Device AST of kernel node is empty");
1207 
1208   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1209   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1210   ValueMapT HostValueMap = ValueMap;
1211   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1212   ScalarMap.clear();
1213 
1214   SetVector<const Loop *> Loops;
1215 
1216   // Create for all loops we depend on values that contain the current loop
1217   // iteration. These values are necessary to generate code for SCEVs that
1218   // depend on such loops. As a result we need to pass them to the subfunction.
1219   for (const Loop *L : Loops) {
1220     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1221                                             SE.getUnknown(Builder.getInt64(1)),
1222                                             L, SCEV::FlagAnyWrap);
1223     Value *V = generateSCEV(OuterLIV);
1224     OutsideLoopIterations[L] = SE.getUnknown(V);
1225     SubtreeValues.insert(V);
1226   }
1227 
1228   createKernelFunction(Kernel, SubtreeValues);
1229 
1230   create(isl_ast_node_copy(Kernel->tree));
1231 
1232   finalizeKernelArguments(Kernel);
1233   Function *F = Builder.GetInsertBlock()->getParent();
1234   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1235   clearDominators(F);
1236   clearScalarEvolution(F);
1237   clearLoops(F);
1238 
1239   IDToValue = HostIDs;
1240 
1241   ValueMap = std::move(HostValueMap);
1242   ScalarMap = std::move(HostScalarMap);
1243   EscapeMap.clear();
1244   IDToSAI.clear();
1245   Annotator.resetAlternativeAliasBases();
1246   for (auto &BasePtr : LocalArrays)
1247     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
1248   LocalArrays.clear();
1249 
1250   std::string ASMString = finalizeKernelFunction();
1251   Builder.SetInsertPoint(&HostInsertPoint);
1252   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1253 
1254   std::string Name = "kernel_" + std::to_string(Kernel->id);
1255   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1256   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1257   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1258 
1259   Value *GridDimX, *GridDimY;
1260   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1261 
1262   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1263                          BlockDimZ, Parameters);
1264   createCallFreeKernel(GPUKernel);
1265 
1266   for (auto Id : KernelIds)
1267     isl_id_free(Id);
1268 
1269   KernelIds.clear();
1270 }
1271 
1272 /// Compute the DataLayout string for the NVPTX backend.
1273 ///
1274 /// @param is64Bit Are we looking for a 64 bit architecture?
1275 static std::string computeNVPTXDataLayout(bool is64Bit) {
1276   std::string Ret = "e";
1277 
1278   if (!is64Bit)
1279     Ret += "-p:32:32";
1280 
1281   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
1282 
1283   return Ret;
1284 }
1285 
1286 Function *
1287 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1288                                          SetVector<Value *> &SubtreeValues) {
1289   std::vector<Type *> Args;
1290   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1291 
1292   for (long i = 0; i < Prog->n_array; i++) {
1293     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1294       continue;
1295 
1296     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1297       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1298       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1299       Args.push_back(SAI->getElementType());
1300     } else {
1301       Args.push_back(Builder.getInt8PtrTy());
1302     }
1303   }
1304 
1305   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1306 
1307   for (long i = 0; i < NumHostIters; i++)
1308     Args.push_back(Builder.getInt64Ty());
1309 
1310   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1311 
1312   for (long i = 0; i < NumVars; i++) {
1313     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1314     Value *Val = IDToValue[Id];
1315     isl_id_free(Id);
1316     Args.push_back(Val->getType());
1317   }
1318 
1319   for (auto *V : SubtreeValues)
1320     Args.push_back(V->getType());
1321 
1322   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1323   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1324                               GPUModule.get());
1325   FN->setCallingConv(CallingConv::PTX_Kernel);
1326 
1327   auto Arg = FN->arg_begin();
1328   for (long i = 0; i < Kernel->n_array; i++) {
1329     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1330       continue;
1331 
1332     Arg->setName(Kernel->array[i].array->name);
1333 
1334     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1335     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1336     Type *EleTy = SAI->getElementType();
1337     Value *Val = &*Arg;
1338     SmallVector<const SCEV *, 4> Sizes;
1339     isl_ast_build *Build =
1340         isl_ast_build_from_context(isl_set_copy(Prog->context));
1341     Sizes.push_back(nullptr);
1342     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1343       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1344           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1345       auto V = ExprBuilder.create(DimSize);
1346       Sizes.push_back(SE.getSCEV(V));
1347     }
1348     const ScopArrayInfo *SAIRep =
1349         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
1350     LocalArrays.push_back(Val);
1351 
1352     isl_ast_build_free(Build);
1353     KernelIds.push_back(Id);
1354     IDToSAI[Id] = SAIRep;
1355     Arg++;
1356   }
1357 
1358   for (long i = 0; i < NumHostIters; i++) {
1359     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1360     Arg->setName(isl_id_get_name(Id));
1361     IDToValue[Id] = &*Arg;
1362     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1363     Arg++;
1364   }
1365 
1366   for (long i = 0; i < NumVars; i++) {
1367     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1368     Arg->setName(isl_id_get_name(Id));
1369     Value *Val = IDToValue[Id];
1370     ValueMap[Val] = &*Arg;
1371     IDToValue[Id] = &*Arg;
1372     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1373     Arg++;
1374   }
1375 
1376   for (auto *V : SubtreeValues) {
1377     Arg->setName(V->getName());
1378     ValueMap[V] = &*Arg;
1379     Arg++;
1380   }
1381 
1382   return FN;
1383 }
1384 
1385 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1386   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1387                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1388 
1389   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1390                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1391                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1392 
1393   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1394     std::string Name = isl_id_get_name(Id);
1395     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1396     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1397     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1398     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1399     IDToValue[Id] = Val;
1400     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1401   };
1402 
1403   for (int i = 0; i < Kernel->n_grid; ++i) {
1404     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1405     addId(Id, IntrinsicsBID[i]);
1406   }
1407 
1408   for (int i = 0; i < Kernel->n_block; ++i) {
1409     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1410     addId(Id, IntrinsicsTID[i]);
1411   }
1412 }
1413 
1414 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1415   auto Arg = FN->arg_begin();
1416   for (long i = 0; i < Kernel->n_array; i++) {
1417     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1418       continue;
1419 
1420     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1421     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1422     isl_id_free(Id);
1423 
1424     if (SAI->getNumberOfDimensions() > 0) {
1425       Arg++;
1426       continue;
1427     }
1428 
1429     Value *Val = &*Arg;
1430 
1431     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
1432       Type *TypePtr = SAI->getElementType()->getPointerTo();
1433       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1434       Val = Builder.CreateLoad(TypedArgPtr);
1435     }
1436 
1437     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1438     Builder.CreateStore(Val, Alloca);
1439 
1440     Arg++;
1441   }
1442 }
1443 
1444 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
1445   auto *FN = Builder.GetInsertBlock()->getParent();
1446   auto Arg = FN->arg_begin();
1447 
1448   bool StoredScalar = false;
1449   for (long i = 0; i < Kernel->n_array; i++) {
1450     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1451       continue;
1452 
1453     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1454     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1455     isl_id_free(Id);
1456 
1457     if (SAI->getNumberOfDimensions() > 0) {
1458       Arg++;
1459       continue;
1460     }
1461 
1462     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1463       Arg++;
1464       continue;
1465     }
1466 
1467     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1468     Value *ArgPtr = &*Arg;
1469     Type *TypePtr = SAI->getElementType()->getPointerTo();
1470     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1471     Value *Val = Builder.CreateLoad(Alloca);
1472     Builder.CreateStore(Val, TypedArgPtr);
1473     StoredScalar = true;
1474 
1475     Arg++;
1476   }
1477 
1478   if (StoredScalar)
1479     /// In case more than one thread contains scalar stores, the generated
1480     /// code might be incorrect, if we only store at the end of the kernel.
1481     /// To support this case we need to store these scalars back at each
1482     /// memory store or at least before each kernel barrier.
1483     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
1484       BuildSuccessful = 0;
1485 }
1486 
1487 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1488   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1489 
1490   for (int i = 0; i < Kernel->n_var; ++i) {
1491     struct ppcg_kernel_var &Var = Kernel->var[i];
1492     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1493     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1494 
1495     Type *ArrayTy = EleTy;
1496     SmallVector<const SCEV *, 4> Sizes;
1497 
1498     Sizes.push_back(nullptr);
1499     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1500       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1501       long Bound = isl_val_get_num_si(Val);
1502       isl_val_free(Val);
1503       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1504     }
1505 
1506     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1507       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1508       long Bound = isl_val_get_num_si(Val);
1509       isl_val_free(Val);
1510       ArrayTy = ArrayType::get(ArrayTy, Bound);
1511     }
1512 
1513     const ScopArrayInfo *SAI;
1514     Value *Allocation;
1515     if (Var.type == ppcg_access_shared) {
1516       auto GlobalVar = new GlobalVariable(
1517           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1518           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1519       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1520       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1521 
1522       Allocation = GlobalVar;
1523     } else if (Var.type == ppcg_access_private) {
1524       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1525     } else {
1526       llvm_unreachable("unknown variable type");
1527     }
1528     SAI =
1529         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1530     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1531     IDToValue[Id] = Allocation;
1532     LocalArrays.push_back(Allocation);
1533     KernelIds.push_back(Id);
1534     IDToSAI[Id] = SAI;
1535   }
1536 }
1537 
1538 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1539                                           SetVector<Value *> &SubtreeValues) {
1540 
1541   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1542   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1543   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1544   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
1545 
1546   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
1547 
1548   BasicBlock *PrevBlock = Builder.GetInsertBlock();
1549   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
1550 
1551   DT.addNewBlock(EntryBlock, PrevBlock);
1552 
1553   Builder.SetInsertPoint(EntryBlock);
1554   Builder.CreateRetVoid();
1555   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1556 
1557   ScopDetection::markFunctionAsInvalid(FN);
1558 
1559   prepareKernelArguments(Kernel, FN);
1560   createKernelVariables(Kernel, FN);
1561   insertKernelIntrinsics(Kernel);
1562 }
1563 
1564 std::string GPUNodeBuilder::createKernelASM() {
1565   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1566   std::string ErrMsg;
1567   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
1568 
1569   if (!GPUTarget) {
1570     errs() << ErrMsg << "\n";
1571     return "";
1572   }
1573 
1574   TargetOptions Options;
1575   Options.UnsafeFPMath = FastMath;
1576   std::unique_ptr<TargetMachine> TargetM(
1577       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
1578                                      Options, Optional<Reloc::Model>()));
1579 
1580   SmallString<0> ASMString;
1581   raw_svector_ostream ASMStream(ASMString);
1582   llvm::legacy::PassManager PM;
1583 
1584   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
1585 
1586   if (TargetM->addPassesToEmitFile(
1587           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
1588     errs() << "The target does not support generation of this file type!\n";
1589     return "";
1590   }
1591 
1592   PM.run(*GPUModule);
1593 
1594   return ASMStream.str();
1595 }
1596 
1597 std::string GPUNodeBuilder::finalizeKernelFunction() {
1598   if (verifyModule(*GPUModule)) {
1599     BuildSuccessful = false;
1600     return "";
1601   }
1602 
1603   if (DumpKernelIR)
1604     outs() << *GPUModule << "\n";
1605 
1606   // Optimize module.
1607   llvm::legacy::PassManager OptPasses;
1608   PassManagerBuilder PassBuilder;
1609   PassBuilder.OptLevel = 3;
1610   PassBuilder.SizeLevel = 0;
1611   PassBuilder.populateModulePassManager(OptPasses);
1612   OptPasses.run(*GPUModule);
1613 
1614   std::string Assembly = createKernelASM();
1615 
1616   if (DumpKernelASM)
1617     outs() << Assembly << "\n";
1618 
1619   GPUModule.release();
1620   KernelIDs.clear();
1621 
1622   return Assembly;
1623 }
1624 
1625 namespace {
1626 class PPCGCodeGeneration : public ScopPass {
1627 public:
1628   static char ID;
1629 
1630   /// The scop that is currently processed.
1631   Scop *S;
1632 
1633   LoopInfo *LI;
1634   DominatorTree *DT;
1635   ScalarEvolution *SE;
1636   const DataLayout *DL;
1637   RegionInfo *RI;
1638 
1639   PPCGCodeGeneration() : ScopPass(ID) {}
1640 
1641   /// Construct compilation options for PPCG.
1642   ///
1643   /// @returns The compilation options.
1644   ppcg_options *createPPCGOptions() {
1645     auto DebugOptions =
1646         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1647     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1648 
1649     DebugOptions->dump_schedule_constraints = false;
1650     DebugOptions->dump_schedule = false;
1651     DebugOptions->dump_final_schedule = false;
1652     DebugOptions->dump_sizes = false;
1653     DebugOptions->verbose = false;
1654 
1655     Options->debug = DebugOptions;
1656 
1657     Options->reschedule = true;
1658     Options->scale_tile_loops = false;
1659     Options->wrap = false;
1660 
1661     Options->non_negative_parameters = false;
1662     Options->ctx = nullptr;
1663     Options->sizes = nullptr;
1664 
1665     Options->tile_size = 32;
1666 
1667     Options->use_private_memory = PrivateMemory;
1668     Options->use_shared_memory = SharedMemory;
1669     Options->max_shared_memory = 48 * 1024;
1670 
1671     Options->target = PPCG_TARGET_CUDA;
1672     Options->openmp = false;
1673     Options->linearize_device_arrays = true;
1674     Options->live_range_reordering = false;
1675 
1676     Options->opencl_compiler_options = nullptr;
1677     Options->opencl_use_gpu = false;
1678     Options->opencl_n_include_file = 0;
1679     Options->opencl_include_files = nullptr;
1680     Options->opencl_print_kernel_types = false;
1681     Options->opencl_embed_kernel_code = false;
1682 
1683     Options->save_schedule_file = nullptr;
1684     Options->load_schedule_file = nullptr;
1685 
1686     return Options;
1687   }
1688 
1689   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1690   ///
1691   /// Instead of a normal access of the form:
1692   ///
1693   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1694   ///
1695   /// a tagged access has the form
1696   ///
1697   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1698   ///
1699   /// where 'id' is an additional space that references the memory access that
1700   /// triggered the access.
1701   ///
1702   /// @param AccessTy The type of the memory accesses to collect.
1703   ///
1704   /// @return The relation describing all tagged memory accesses.
1705   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1706     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1707 
1708     for (auto &Stmt : *S)
1709       for (auto &Acc : Stmt)
1710         if (Acc->getType() == AccessTy) {
1711           isl_map *Relation = Acc->getAccessRelation();
1712           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1713 
1714           isl_space *Space = isl_map_get_space(Relation);
1715           Space = isl_space_range(Space);
1716           Space = isl_space_from_range(Space);
1717           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1718           isl_map *Universe = isl_map_universe(Space);
1719           Relation = isl_map_domain_product(Relation, Universe);
1720           Accesses = isl_union_map_add_map(Accesses, Relation);
1721         }
1722 
1723     return Accesses;
1724   }
1725 
1726   /// Get the set of all read accesses, tagged with the access id.
1727   ///
1728   /// @see getTaggedAccesses
1729   isl_union_map *getTaggedReads() {
1730     return getTaggedAccesses(MemoryAccess::READ);
1731   }
1732 
1733   /// Get the set of all may (and must) accesses, tagged with the access id.
1734   ///
1735   /// @see getTaggedAccesses
1736   isl_union_map *getTaggedMayWrites() {
1737     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1738                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1739   }
1740 
1741   /// Get the set of all must accesses, tagged with the access id.
1742   ///
1743   /// @see getTaggedAccesses
1744   isl_union_map *getTaggedMustWrites() {
1745     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1746   }
1747 
1748   /// Collect parameter and array names as isl_ids.
1749   ///
1750   /// To reason about the different parameters and arrays used, ppcg requires
1751   /// a list of all isl_ids in use. As PPCG traditionally performs
1752   /// source-to-source compilation each of these isl_ids is mapped to the
1753   /// expression that represents it. As we do not have a corresponding
1754   /// expression in Polly, we just map each id to a 'zero' expression to match
1755   /// the data format that ppcg expects.
1756   ///
1757   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1758   __isl_give isl_id_to_ast_expr *getNames() {
1759     auto *Names = isl_id_to_ast_expr_alloc(
1760         S->getIslCtx(),
1761         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1762     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1763     auto *Space = S->getParamSpace();
1764 
1765     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1766       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1767       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1768     }
1769 
1770     for (auto &Array : S->arrays()) {
1771       auto Id = Array->getBasePtrId();
1772       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1773     }
1774 
1775     isl_space_free(Space);
1776     isl_ast_expr_free(Zero);
1777 
1778     return Names;
1779   }
1780 
1781   /// Create a new PPCG scop from the current scop.
1782   ///
1783   /// The PPCG scop is initialized with data from the current polly::Scop. From
1784   /// this initial data, the data-dependences in the PPCG scop are initialized.
1785   /// We do not use Polly's dependence analysis for now, to ensure we match
1786   /// the PPCG default behaviour more closely.
1787   ///
1788   /// @returns A new ppcg scop.
1789   ppcg_scop *createPPCGScop() {
1790     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1791 
1792     PPCGScop->options = createPPCGOptions();
1793 
1794     PPCGScop->start = 0;
1795     PPCGScop->end = 0;
1796 
1797     PPCGScop->context = S->getContext();
1798     PPCGScop->domain = S->getDomains();
1799     PPCGScop->call = nullptr;
1800     PPCGScop->tagged_reads = getTaggedReads();
1801     PPCGScop->reads = S->getReads();
1802     PPCGScop->live_in = nullptr;
1803     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1804     PPCGScop->may_writes = S->getWrites();
1805     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1806     PPCGScop->must_writes = S->getMustWrites();
1807     PPCGScop->live_out = nullptr;
1808     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1809     PPCGScop->tagger = nullptr;
1810 
1811     PPCGScop->independence = nullptr;
1812     PPCGScop->dep_flow = nullptr;
1813     PPCGScop->tagged_dep_flow = nullptr;
1814     PPCGScop->dep_false = nullptr;
1815     PPCGScop->dep_forced = nullptr;
1816     PPCGScop->dep_order = nullptr;
1817     PPCGScop->tagged_dep_order = nullptr;
1818 
1819     PPCGScop->schedule = S->getScheduleTree();
1820     PPCGScop->names = getNames();
1821 
1822     PPCGScop->pet = nullptr;
1823 
1824     compute_tagger(PPCGScop);
1825     compute_dependences(PPCGScop);
1826 
1827     return PPCGScop;
1828   }
1829 
1830   /// Collect the array acesses in a statement.
1831   ///
1832   /// @param Stmt The statement for which to collect the accesses.
1833   ///
1834   /// @returns A list of array accesses.
1835   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1836     gpu_stmt_access *Accesses = nullptr;
1837 
1838     for (MemoryAccess *Acc : Stmt) {
1839       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1840       Access->read = Acc->isRead();
1841       Access->write = Acc->isWrite();
1842       Access->access = Acc->getAccessRelation();
1843       isl_space *Space = isl_map_get_space(Access->access);
1844       Space = isl_space_range(Space);
1845       Space = isl_space_from_range(Space);
1846       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1847       isl_map *Universe = isl_map_universe(Space);
1848       Access->tagged_access =
1849           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1850       Access->exact_write = !Acc->isMayWrite();
1851       Access->ref_id = Acc->getId();
1852       Access->next = Accesses;
1853       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
1854       Accesses = Access;
1855     }
1856 
1857     return Accesses;
1858   }
1859 
1860   /// Collect the list of GPU statements.
1861   ///
1862   /// Each statement has an id, a pointer to the underlying data structure,
1863   /// as well as a list with all memory accesses.
1864   ///
1865   /// TODO: Initialize the list of memory accesses.
1866   ///
1867   /// @returns A linked-list of statements.
1868   gpu_stmt *getStatements() {
1869     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1870                                        std::distance(S->begin(), S->end()));
1871 
1872     int i = 0;
1873     for (auto &Stmt : *S) {
1874       gpu_stmt *GPUStmt = &Stmts[i];
1875 
1876       GPUStmt->id = Stmt.getDomainId();
1877 
1878       // We use the pet stmt pointer to keep track of the Polly statements.
1879       GPUStmt->stmt = (pet_stmt *)&Stmt;
1880       GPUStmt->accesses = getStmtAccesses(Stmt);
1881       i++;
1882     }
1883 
1884     return Stmts;
1885   }
1886 
1887   /// Derive the extent of an array.
1888   ///
1889   /// The extent of an array is the set of elements that are within the
1890   /// accessed array. For the inner dimensions, the extent constraints are
1891   /// 0 and the size of the corresponding array dimension. For the first
1892   /// (outermost) dimension, the extent constraints are the minimal and maximal
1893   /// subscript value for the first dimension.
1894   ///
1895   /// @param Array The array to derive the extent for.
1896   ///
1897   /// @returns An isl_set describing the extent of the array.
1898   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1899     unsigned NumDims = Array->getNumberOfDimensions();
1900     isl_union_map *Accesses = S->getAccesses();
1901     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1902     Accesses = isl_union_map_detect_equalities(Accesses);
1903     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1904     AccessUSet = isl_union_set_coalesce(AccessUSet);
1905     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1906     AccessUSet = isl_union_set_coalesce(AccessUSet);
1907 
1908     if (isl_union_set_is_empty(AccessUSet)) {
1909       isl_union_set_free(AccessUSet);
1910       return isl_set_empty(Array->getSpace());
1911     }
1912 
1913     if (Array->getNumberOfDimensions() == 0) {
1914       isl_union_set_free(AccessUSet);
1915       return isl_set_universe(Array->getSpace());
1916     }
1917 
1918     isl_set *AccessSet =
1919         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1920 
1921     isl_union_set_free(AccessUSet);
1922     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1923 
1924     isl_pw_aff *Val =
1925         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1926 
1927     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1928     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1929     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1930                                    isl_pw_aff_dim(Val, isl_dim_in));
1931     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1932                                    isl_pw_aff_dim(Val, isl_dim_in));
1933     OuterMin =
1934         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1935     OuterMax =
1936         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1937 
1938     isl_set *Extent = isl_set_universe(Array->getSpace());
1939 
1940     Extent = isl_set_intersect(
1941         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1942     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1943 
1944     for (unsigned i = 1; i < NumDims; ++i)
1945       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1946 
1947     for (unsigned i = 1; i < NumDims; ++i) {
1948       isl_pw_aff *PwAff =
1949           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1950       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1951           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1952       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1953                                   isl_pw_aff_dim(Val, isl_dim_in));
1954       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1955                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1956       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1957       Extent = isl_set_intersect(Set, Extent);
1958     }
1959 
1960     return Extent;
1961   }
1962 
1963   /// Derive the bounds of an array.
1964   ///
1965   /// For the first dimension we derive the bound of the array from the extent
1966   /// of this dimension. For inner dimensions we obtain their size directly from
1967   /// ScopArrayInfo.
1968   ///
1969   /// @param PPCGArray The array to compute bounds for.
1970   /// @param Array The polly array from which to take the information.
1971   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1972     if (PPCGArray.n_index > 0) {
1973       if (isl_set_is_empty(PPCGArray.extent)) {
1974         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1975         isl_local_space *LS = isl_local_space_from_space(
1976             isl_space_params(isl_set_get_space(Dom)));
1977         isl_set_free(Dom);
1978         isl_aff *Zero = isl_aff_zero_on_domain(LS);
1979         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
1980       } else {
1981         isl_set *Dom = isl_set_copy(PPCGArray.extent);
1982         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1983         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1984         isl_set_free(Dom);
1985         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1986         isl_local_space *LS =
1987             isl_local_space_from_space(isl_set_get_space(Dom));
1988         isl_aff *One = isl_aff_zero_on_domain(LS);
1989         One = isl_aff_add_constant_si(One, 1);
1990         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1991         Bound = isl_pw_aff_gist(Bound, S->getContext());
1992         PPCGArray.bound[0] = Bound;
1993       }
1994     }
1995 
1996     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1997       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1998       auto LS = isl_pw_aff_get_domain_space(Bound);
1999       auto Aff = isl_multi_aff_zero(LS);
2000       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2001       PPCGArray.bound[i] = Bound;
2002     }
2003   }
2004 
2005   /// Create the arrays for @p PPCGProg.
2006   ///
2007   /// @param PPCGProg The program to compute the arrays for.
2008   void createArrays(gpu_prog *PPCGProg) {
2009     int i = 0;
2010     for (auto &Array : S->arrays()) {
2011       std::string TypeName;
2012       raw_string_ostream OS(TypeName);
2013 
2014       OS << *Array->getElementType();
2015       TypeName = OS.str();
2016 
2017       gpu_array_info &PPCGArray = PPCGProg->array[i];
2018 
2019       PPCGArray.space = Array->getSpace();
2020       PPCGArray.type = strdup(TypeName.c_str());
2021       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
2022       PPCGArray.name = strdup(Array->getName().c_str());
2023       PPCGArray.extent = nullptr;
2024       PPCGArray.n_index = Array->getNumberOfDimensions();
2025       PPCGArray.bound =
2026           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
2027       PPCGArray.extent = getExtent(Array);
2028       PPCGArray.n_ref = 0;
2029       PPCGArray.refs = nullptr;
2030       PPCGArray.accessed = true;
2031       PPCGArray.read_only_scalar =
2032           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
2033       PPCGArray.has_compound_element = false;
2034       PPCGArray.local = false;
2035       PPCGArray.declare_local = false;
2036       PPCGArray.global = false;
2037       PPCGArray.linearize = false;
2038       PPCGArray.dep_order = nullptr;
2039       PPCGArray.user = Array;
2040 
2041       setArrayBounds(PPCGArray, Array);
2042       i++;
2043 
2044       collect_references(PPCGProg, &PPCGArray);
2045     }
2046   }
2047 
2048   /// Create an identity map between the arrays in the scop.
2049   ///
2050   /// @returns An identity map between the arrays in the scop.
2051   isl_union_map *getArrayIdentity() {
2052     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
2053 
2054     for (auto &Array : S->arrays()) {
2055       isl_space *Space = Array->getSpace();
2056       Space = isl_space_map_from_set(Space);
2057       isl_map *Identity = isl_map_identity(Space);
2058       Maps = isl_union_map_add_map(Maps, Identity);
2059     }
2060 
2061     return Maps;
2062   }
2063 
2064   /// Create a default-initialized PPCG GPU program.
2065   ///
2066   /// @returns A new gpu grogram description.
2067   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2068 
2069     if (!PPCGScop)
2070       return nullptr;
2071 
2072     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2073 
2074     PPCGProg->ctx = S->getIslCtx();
2075     PPCGProg->scop = PPCGScop;
2076     PPCGProg->context = isl_set_copy(PPCGScop->context);
2077     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
2078     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
2079     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
2080     PPCGProg->tagged_must_kill =
2081         isl_union_map_copy(PPCGScop->tagged_must_kills);
2082     PPCGProg->to_inner = getArrayIdentity();
2083     PPCGProg->to_outer = getArrayIdentity();
2084     PPCGProg->any_to_outer = nullptr;
2085     PPCGProg->array_order = nullptr;
2086     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
2087     PPCGProg->stmts = getStatements();
2088     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
2089     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
2090                                        PPCGProg->n_array);
2091 
2092     createArrays(PPCGProg);
2093 
2094     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2095 
2096     return PPCGProg;
2097   }
2098 
2099   struct PrintGPUUserData {
2100     struct cuda_info *CudaInfo;
2101     struct gpu_prog *PPCGProg;
2102     std::vector<ppcg_kernel *> Kernels;
2103   };
2104 
2105   /// Print a user statement node in the host code.
2106   ///
2107   /// We use ppcg's printing facilities to print the actual statement and
2108   /// additionally build up a list of all kernels that are encountered in the
2109   /// host ast.
2110   ///
2111   /// @param P The printer to print to
2112   /// @param Options The printing options to use
2113   /// @param Node The node to print
2114   /// @param User A user pointer to carry additional data. This pointer is
2115   ///             expected to be of type PrintGPUUserData.
2116   ///
2117   /// @returns A printer to which the output has been printed.
2118   static __isl_give isl_printer *
2119   printHostUser(__isl_take isl_printer *P,
2120                 __isl_take isl_ast_print_options *Options,
2121                 __isl_take isl_ast_node *Node, void *User) {
2122     auto Data = (struct PrintGPUUserData *)User;
2123     auto Id = isl_ast_node_get_annotation(Node);
2124 
2125     if (Id) {
2126       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
2127 
2128       // If this is a user statement, format it ourselves as ppcg would
2129       // otherwise try to call pet functionality that is not available in
2130       // Polly.
2131       if (IsUser) {
2132         P = isl_printer_start_line(P);
2133         P = isl_printer_print_ast_node(P, Node);
2134         P = isl_printer_end_line(P);
2135         isl_id_free(Id);
2136         isl_ast_print_options_free(Options);
2137         return P;
2138       }
2139 
2140       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
2141       isl_id_free(Id);
2142       Data->Kernels.push_back(Kernel);
2143     }
2144 
2145     return print_host_user(P, Options, Node, User);
2146   }
2147 
2148   /// Print C code corresponding to the control flow in @p Kernel.
2149   ///
2150   /// @param Kernel The kernel to print
2151   void printKernel(ppcg_kernel *Kernel) {
2152     auto *P = isl_printer_to_str(S->getIslCtx());
2153     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2154     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2155     P = isl_ast_node_print(Kernel->tree, P, Options);
2156     char *String = isl_printer_get_str(P);
2157     printf("%s\n", String);
2158     free(String);
2159     isl_printer_free(P);
2160   }
2161 
2162   /// Print C code corresponding to the GPU code described by @p Tree.
2163   ///
2164   /// @param Tree An AST describing GPU code
2165   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
2166   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
2167     auto *P = isl_printer_to_str(S->getIslCtx());
2168     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2169 
2170     PrintGPUUserData Data;
2171     Data.PPCGProg = PPCGProg;
2172 
2173     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2174     Options =
2175         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
2176     P = isl_ast_node_print(Tree, P, Options);
2177     char *String = isl_printer_get_str(P);
2178     printf("# host\n");
2179     printf("%s\n", String);
2180     free(String);
2181     isl_printer_free(P);
2182 
2183     for (auto Kernel : Data.Kernels) {
2184       printf("# kernel%d\n", Kernel->id);
2185       printKernel(Kernel);
2186     }
2187   }
2188 
2189   // Generate a GPU program using PPCG.
2190   //
2191   // GPU mapping consists of multiple steps:
2192   //
2193   //  1) Compute new schedule for the program.
2194   //  2) Map schedule to GPU (TODO)
2195   //  3) Generate code for new schedule (TODO)
2196   //
2197   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2198   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2199   // strategy directly from this pass.
2200   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2201 
2202     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2203 
2204     PPCGGen->ctx = S->getIslCtx();
2205     PPCGGen->options = PPCGScop->options;
2206     PPCGGen->print = nullptr;
2207     PPCGGen->print_user = nullptr;
2208     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2209     PPCGGen->prog = PPCGProg;
2210     PPCGGen->tree = nullptr;
2211     PPCGGen->types.n = 0;
2212     PPCGGen->types.name = nullptr;
2213     PPCGGen->sizes = nullptr;
2214     PPCGGen->used_sizes = nullptr;
2215     PPCGGen->kernel_id = 0;
2216 
2217     // Set scheduling strategy to same strategy PPCG is using.
2218     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2219     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
2220     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2221 
2222     isl_schedule *Schedule = get_schedule(PPCGGen);
2223 
2224     int has_permutable = has_any_permutable_node(Schedule);
2225 
2226     if (!has_permutable || has_permutable < 0) {
2227       Schedule = isl_schedule_free(Schedule);
2228     } else {
2229       Schedule = map_to_device(PPCGGen, Schedule);
2230       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
2231     }
2232 
2233     if (DumpSchedule) {
2234       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2235       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2236       P = isl_printer_print_str(P, "Schedule\n");
2237       P = isl_printer_print_str(P, "========\n");
2238       if (Schedule)
2239         P = isl_printer_print_schedule(P, Schedule);
2240       else
2241         P = isl_printer_print_str(P, "No schedule found\n");
2242 
2243       printf("%s\n", isl_printer_get_str(P));
2244       isl_printer_free(P);
2245     }
2246 
2247     if (DumpCode) {
2248       printf("Code\n");
2249       printf("====\n");
2250       if (PPCGGen->tree)
2251         printGPUTree(PPCGGen->tree, PPCGProg);
2252       else
2253         printf("No code generated\n");
2254     }
2255 
2256     isl_schedule_free(Schedule);
2257 
2258     return PPCGGen;
2259   }
2260 
2261   /// Free gpu_gen structure.
2262   ///
2263   /// @param PPCGGen The ppcg_gen object to free.
2264   void freePPCGGen(gpu_gen *PPCGGen) {
2265     isl_ast_node_free(PPCGGen->tree);
2266     isl_union_map_free(PPCGGen->sizes);
2267     isl_union_map_free(PPCGGen->used_sizes);
2268     free(PPCGGen);
2269   }
2270 
2271   /// Free the options in the ppcg scop structure.
2272   ///
2273   /// ppcg is not freeing these options for us. To avoid leaks we do this
2274   /// ourselves.
2275   ///
2276   /// @param PPCGScop The scop referencing the options to free.
2277   void freeOptions(ppcg_scop *PPCGScop) {
2278     free(PPCGScop->options->debug);
2279     PPCGScop->options->debug = nullptr;
2280     free(PPCGScop->options);
2281     PPCGScop->options = nullptr;
2282   }
2283 
2284   /// Approximate the number of points in the set.
2285   ///
2286   /// This function returns an ast expression that overapproximates the number
2287   /// of points in an isl set through the rectangular hull surrounding this set.
2288   ///
2289   /// @param Set   The set to count.
2290   /// @param Build The isl ast build object to use for creating the ast
2291   ///              expression.
2292   ///
2293   /// @returns An approximation of the number of points in the set.
2294   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
2295                                              __isl_keep isl_ast_build *Build) {
2296 
2297     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
2298     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
2299 
2300     isl_space *Space = isl_set_get_space(Set);
2301     Space = isl_space_params(Space);
2302     auto *Univ = isl_set_universe(Space);
2303     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
2304 
2305     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
2306       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
2307       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
2308       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
2309       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
2310       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
2311       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
2312     }
2313 
2314     isl_set_free(Set);
2315     isl_pw_aff_free(OneAff);
2316 
2317     return Expr;
2318   }
2319 
2320   /// Approximate a number of dynamic instructions executed by a given
2321   /// statement.
2322   ///
2323   /// @param Stmt  The statement for which to compute the number of dynamic
2324   ///              instructions.
2325   /// @param Build The isl ast build object to use for creating the ast
2326   ///              expression.
2327   /// @returns An approximation of the number of dynamic instructions executed
2328   ///          by @p Stmt.
2329   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
2330                                              __isl_keep isl_ast_build *Build) {
2331     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
2332 
2333     long InstCount = 0;
2334 
2335     if (Stmt.isBlockStmt()) {
2336       auto *BB = Stmt.getBasicBlock();
2337       InstCount = std::distance(BB->begin(), BB->end());
2338     } else {
2339       auto *R = Stmt.getRegion();
2340 
2341       for (auto *BB : R->blocks()) {
2342         InstCount += std::distance(BB->begin(), BB->end());
2343       }
2344     }
2345 
2346     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
2347     auto *InstExpr = isl_ast_expr_from_val(InstVal);
2348     return isl_ast_expr_mul(InstExpr, Iterations);
2349   }
2350 
2351   /// Approximate dynamic instructions executed in scop.
2352   ///
2353   /// @param S     The scop for which to approximate dynamic instructions.
2354   /// @param Build The isl ast build object to use for creating the ast
2355   ///              expression.
2356   /// @returns An approximation of the number of dynamic instructions executed
2357   ///          in @p S.
2358   __isl_give isl_ast_expr *
2359   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
2360     isl_ast_expr *Instructions;
2361 
2362     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
2363     Instructions = isl_ast_expr_from_val(Zero);
2364 
2365     for (ScopStmt &Stmt : S) {
2366       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
2367       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
2368     }
2369     return Instructions;
2370   }
2371 
2372   /// Create a check that ensures sufficient compute in scop.
2373   ///
2374   /// @param S     The scop for which to ensure sufficient compute.
2375   /// @param Build The isl ast build object to use for creating the ast
2376   ///              expression.
2377   /// @returns An expression that evaluates to TRUE in case of sufficient
2378   ///          compute and to FALSE, otherwise.
2379   __isl_give isl_ast_expr *
2380   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
2381     auto Iterations = getNumberOfIterations(S, Build);
2382     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
2383     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
2384     return isl_ast_expr_ge(Iterations, MinComputeExpr);
2385   }
2386 
2387   /// Generate code for a given GPU AST described by @p Root.
2388   ///
2389   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
2390   /// @param Prog The GPU Program to generate code for.
2391   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
2392     ScopAnnotator Annotator;
2393     Annotator.buildAliasScopes(*S);
2394 
2395     Region *R = &S->getRegion();
2396 
2397     simplifyRegion(R, DT, LI, RI);
2398 
2399     BasicBlock *EnteringBB = R->getEnteringBlock();
2400 
2401     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
2402 
2403     // Only build the run-time condition and parameters _after_ having
2404     // introduced the conditional branch. This is important as the conditional
2405     // branch will guard the original scop from new induction variables that
2406     // the SCEVExpander may introduce while code generating the parameters and
2407     // which may introduce scalar dependences that prevent us from correctly
2408     // code generating this scop.
2409     BasicBlock *StartBlock =
2410         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
2411 
2412     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
2413                                StartBlock, Prog);
2414 
2415     // TODO: Handle LICM
2416     auto SplitBlock = StartBlock->getSinglePredecessor();
2417     Builder.SetInsertPoint(SplitBlock->getTerminator());
2418     NodeBuilder.addParameters(S->getContext());
2419 
2420     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2421     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2422     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
2423     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2424     isl_ast_build_free(Build);
2425 
2426     Value *RTC = NodeBuilder.createRTC(Condition);
2427     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2428 
2429     Builder.SetInsertPoint(&*StartBlock->begin());
2430 
2431     NodeBuilder.initializeAfterRTH();
2432     NodeBuilder.create(Root);
2433     NodeBuilder.finalize();
2434 
2435     /// In case a sequential kernel has more surrounding loops as any parallel
2436     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2437     /// point in running it on a GPU.
2438     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2439       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2440 
2441     if (!NodeBuilder.BuildSuccessful)
2442       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2443   }
2444 
2445   bool runOnScop(Scop &CurrentScop) override {
2446     S = &CurrentScop;
2447     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2448     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2449     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2450     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
2451     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2452 
2453     // We currently do not support scops with invariant loads.
2454     if (S->hasInvariantAccesses())
2455       return false;
2456 
2457     auto PPCGScop = createPPCGScop();
2458     auto PPCGProg = createPPCGProg(PPCGScop);
2459     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
2460 
2461     if (PPCGGen->tree)
2462       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
2463 
2464     freeOptions(PPCGScop);
2465     freePPCGGen(PPCGGen);
2466     gpu_prog_free(PPCGProg);
2467     ppcg_scop_free(PPCGScop);
2468 
2469     return true;
2470   }
2471 
2472   void printScop(raw_ostream &, Scop &) const override {}
2473 
2474   void getAnalysisUsage(AnalysisUsage &AU) const override {
2475     AU.addRequired<DominatorTreeWrapperPass>();
2476     AU.addRequired<RegionInfoPass>();
2477     AU.addRequired<ScalarEvolutionWrapperPass>();
2478     AU.addRequired<ScopDetection>();
2479     AU.addRequired<ScopInfoRegionPass>();
2480     AU.addRequired<LoopInfoWrapperPass>();
2481 
2482     AU.addPreserved<AAResultsWrapperPass>();
2483     AU.addPreserved<BasicAAWrapperPass>();
2484     AU.addPreserved<LoopInfoWrapperPass>();
2485     AU.addPreserved<DominatorTreeWrapperPass>();
2486     AU.addPreserved<GlobalsAAWrapperPass>();
2487     AU.addPreserved<ScopDetection>();
2488     AU.addPreserved<ScalarEvolutionWrapperPass>();
2489     AU.addPreserved<SCEVAAWrapperPass>();
2490 
2491     // FIXME: We do not yet add regions for the newly generated code to the
2492     //        region tree.
2493     AU.addPreserved<RegionInfoPass>();
2494     AU.addPreserved<ScopInfoRegionPass>();
2495   }
2496 };
2497 } // namespace
2498 
2499 char PPCGCodeGeneration::ID = 1;
2500 
2501 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
2502 
2503 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
2504                       "Polly - Apply PPCG translation to SCOP", false, false)
2505 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
2506 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2507 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2508 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2509 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2510 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
2511 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
2512                     "Polly - Apply PPCG translation to SCOP", false, false)
2513