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