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