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