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