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