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