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