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