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