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   auto Location = EntryBlock->getTerminator();
915   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
916                          Launch + "_params_i8ptr", Location);
917 }
918 
919 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
920   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
921   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
922   isl_id_free(Id);
923   isl_ast_node_free(KernelStmt);
924 
925   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
926 
927   assert(Kernel->tree && "Device AST of kernel node is empty");
928 
929   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
930   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
931   ValueMapT HostValueMap = ValueMap;
932 
933   SetVector<const Loop *> Loops;
934 
935   // Create for all loops we depend on values that contain the current loop
936   // iteration. These values are necessary to generate code for SCEVs that
937   // depend on such loops. As a result we need to pass them to the subfunction.
938   for (const Loop *L : Loops) {
939     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
940                                             SE.getUnknown(Builder.getInt64(1)),
941                                             L, SCEV::FlagAnyWrap);
942     Value *V = generateSCEV(OuterLIV);
943     OutsideLoopIterations[L] = SE.getUnknown(V);
944     SubtreeValues.insert(V);
945   }
946 
947   createKernelFunction(Kernel, SubtreeValues);
948 
949   create(isl_ast_node_copy(Kernel->tree));
950 
951   Function *F = Builder.GetInsertBlock()->getParent();
952   clearDominators(F);
953   clearScalarEvolution(F);
954   clearLoops(F);
955 
956   Builder.SetInsertPoint(&HostInsertPoint);
957   IDToValue = HostIDs;
958 
959   ValueMap = HostValueMap;
960   ScalarMap.clear();
961   PHIOpMap.clear();
962   EscapeMap.clear();
963   IDToSAI.clear();
964   Annotator.resetAlternativeAliasBases();
965   for (auto &BasePtr : LocalArrays)
966     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
967   LocalArrays.clear();
968 
969   Value *Parameters = createLaunchParameters(Kernel, F);
970 
971   std::string ASMString = finalizeKernelFunction();
972   std::string Name = "kernel_" + std::to_string(Kernel->id);
973   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
974   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
975   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
976 
977   Value *GridDimX, *GridDimY;
978   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
979 
980   Value *BlockDimX, *BlockDimY, *BlockDimZ;
981   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
982 
983   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
984                          BlockDimZ, Parameters);
985   createCallFreeKernel(GPUKernel);
986 }
987 
988 /// Compute the DataLayout string for the NVPTX backend.
989 ///
990 /// @param is64Bit Are we looking for a 64 bit architecture?
991 static std::string computeNVPTXDataLayout(bool is64Bit) {
992   std::string Ret = "e";
993 
994   if (!is64Bit)
995     Ret += "-p:32:32";
996 
997   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
998 
999   return Ret;
1000 }
1001 
1002 Function *
1003 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1004                                          SetVector<Value *> &SubtreeValues) {
1005   std::vector<Type *> Args;
1006   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1007 
1008   for (long i = 0; i < Prog->n_array; i++) {
1009     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1010       continue;
1011 
1012     Args.push_back(Builder.getInt8PtrTy());
1013   }
1014 
1015   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1016 
1017   for (long i = 0; i < NumHostIters; i++)
1018     Args.push_back(Builder.getInt64Ty());
1019 
1020   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1021 
1022   for (long i = 0; i < NumVars; i++)
1023     Args.push_back(Builder.getInt64Ty());
1024 
1025   for (auto *V : SubtreeValues)
1026     Args.push_back(V->getType());
1027 
1028   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1029   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1030                               GPUModule.get());
1031   FN->setCallingConv(CallingConv::PTX_Kernel);
1032 
1033   auto Arg = FN->arg_begin();
1034   for (long i = 0; i < Kernel->n_array; i++) {
1035     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1036       continue;
1037 
1038     Arg->setName(Kernel->array[i].array->name);
1039 
1040     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1041     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1042     Type *EleTy = SAI->getElementType();
1043     Value *Val = &*Arg;
1044     SmallVector<const SCEV *, 4> Sizes;
1045     isl_ast_build *Build =
1046         isl_ast_build_from_context(isl_set_copy(Prog->context));
1047     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1048       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1049           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1050       auto V = ExprBuilder.create(DimSize);
1051       Sizes.push_back(SE.getSCEV(V));
1052     }
1053     const ScopArrayInfo *SAIRep =
1054         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
1055     LocalArrays.push_back(Val);
1056 
1057     isl_ast_build_free(Build);
1058     isl_id_free(Id);
1059     IDToSAI[Id] = SAIRep;
1060     Arg++;
1061   }
1062 
1063   for (long i = 0; i < NumHostIters; i++) {
1064     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1065     Arg->setName(isl_id_get_name(Id));
1066     IDToValue[Id] = &*Arg;
1067     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1068     Arg++;
1069   }
1070 
1071   for (long i = 0; i < NumVars; i++) {
1072     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1073     Arg->setName(isl_id_get_name(Id));
1074     IDToValue[Id] = &*Arg;
1075     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1076     Arg++;
1077   }
1078 
1079   for (auto *V : SubtreeValues) {
1080     Arg->setName(V->getName());
1081     ValueMap[V] = &*Arg;
1082     Arg++;
1083   }
1084 
1085   return FN;
1086 }
1087 
1088 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1089   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1090                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1091 
1092   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1093                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1094                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1095 
1096   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1097     std::string Name = isl_id_get_name(Id);
1098     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1099     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1100     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1101     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1102     IDToValue[Id] = Val;
1103     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1104   };
1105 
1106   for (int i = 0; i < Kernel->n_grid; ++i) {
1107     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1108     addId(Id, IntrinsicsBID[i]);
1109   }
1110 
1111   for (int i = 0; i < Kernel->n_block; ++i) {
1112     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1113     addId(Id, IntrinsicsTID[i]);
1114   }
1115 }
1116 
1117 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1118                                           SetVector<Value *> &SubtreeValues) {
1119 
1120   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
1121   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1122   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1123   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
1124 
1125   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
1126 
1127   BasicBlock *PrevBlock = Builder.GetInsertBlock();
1128   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
1129 
1130   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1131   DT.addNewBlock(EntryBlock, PrevBlock);
1132 
1133   Builder.SetInsertPoint(EntryBlock);
1134   Builder.CreateRetVoid();
1135   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1136 
1137   insertKernelIntrinsics(Kernel);
1138 }
1139 
1140 std::string GPUNodeBuilder::createKernelASM() {
1141   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
1142   std::string ErrMsg;
1143   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
1144 
1145   if (!GPUTarget) {
1146     errs() << ErrMsg << "\n";
1147     return "";
1148   }
1149 
1150   TargetOptions Options;
1151   Options.UnsafeFPMath = FastMath;
1152   std::unique_ptr<TargetMachine> TargetM(
1153       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
1154                                      Options, Optional<Reloc::Model>()));
1155 
1156   SmallString<0> ASMString;
1157   raw_svector_ostream ASMStream(ASMString);
1158   llvm::legacy::PassManager PM;
1159 
1160   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
1161 
1162   if (TargetM->addPassesToEmitFile(
1163           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
1164     errs() << "The target does not support generation of this file type!\n";
1165     return "";
1166   }
1167 
1168   PM.run(*GPUModule);
1169 
1170   return ASMStream.str();
1171 }
1172 
1173 std::string GPUNodeBuilder::finalizeKernelFunction() {
1174   // Verify module.
1175   llvm::legacy::PassManager Passes;
1176   Passes.add(createVerifierPass());
1177   Passes.run(*GPUModule);
1178 
1179   if (DumpKernelIR)
1180     outs() << *GPUModule << "\n";
1181 
1182   // Optimize module.
1183   llvm::legacy::PassManager OptPasses;
1184   PassManagerBuilder PassBuilder;
1185   PassBuilder.OptLevel = 3;
1186   PassBuilder.SizeLevel = 0;
1187   PassBuilder.populateModulePassManager(OptPasses);
1188   OptPasses.run(*GPUModule);
1189 
1190   std::string Assembly = createKernelASM();
1191 
1192   if (DumpKernelASM)
1193     outs() << Assembly << "\n";
1194 
1195   GPUModule.release();
1196   KernelIDs.clear();
1197 
1198   return Assembly;
1199 }
1200 
1201 namespace {
1202 class PPCGCodeGeneration : public ScopPass {
1203 public:
1204   static char ID;
1205 
1206   /// The scop that is currently processed.
1207   Scop *S;
1208 
1209   LoopInfo *LI;
1210   DominatorTree *DT;
1211   ScalarEvolution *SE;
1212   const DataLayout *DL;
1213   RegionInfo *RI;
1214 
1215   PPCGCodeGeneration() : ScopPass(ID) {}
1216 
1217   /// Construct compilation options for PPCG.
1218   ///
1219   /// @returns The compilation options.
1220   ppcg_options *createPPCGOptions() {
1221     auto DebugOptions =
1222         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1223     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1224 
1225     DebugOptions->dump_schedule_constraints = false;
1226     DebugOptions->dump_schedule = false;
1227     DebugOptions->dump_final_schedule = false;
1228     DebugOptions->dump_sizes = false;
1229 
1230     Options->debug = DebugOptions;
1231 
1232     Options->reschedule = true;
1233     Options->scale_tile_loops = false;
1234     Options->wrap = false;
1235 
1236     Options->non_negative_parameters = false;
1237     Options->ctx = nullptr;
1238     Options->sizes = nullptr;
1239 
1240     Options->tile_size = 32;
1241 
1242     Options->use_private_memory = false;
1243     Options->use_shared_memory = false;
1244     Options->max_shared_memory = 0;
1245 
1246     Options->target = PPCG_TARGET_CUDA;
1247     Options->openmp = false;
1248     Options->linearize_device_arrays = true;
1249     Options->live_range_reordering = false;
1250 
1251     Options->opencl_compiler_options = nullptr;
1252     Options->opencl_use_gpu = false;
1253     Options->opencl_n_include_file = 0;
1254     Options->opencl_include_files = nullptr;
1255     Options->opencl_print_kernel_types = false;
1256     Options->opencl_embed_kernel_code = false;
1257 
1258     Options->save_schedule_file = nullptr;
1259     Options->load_schedule_file = nullptr;
1260 
1261     return Options;
1262   }
1263 
1264   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1265   ///
1266   /// Instead of a normal access of the form:
1267   ///
1268   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1269   ///
1270   /// a tagged access has the form
1271   ///
1272   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1273   ///
1274   /// where 'id' is an additional space that references the memory access that
1275   /// triggered the access.
1276   ///
1277   /// @param AccessTy The type of the memory accesses to collect.
1278   ///
1279   /// @return The relation describing all tagged memory accesses.
1280   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1281     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1282 
1283     for (auto &Stmt : *S)
1284       for (auto &Acc : Stmt)
1285         if (Acc->getType() == AccessTy) {
1286           isl_map *Relation = Acc->getAccessRelation();
1287           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1288 
1289           isl_space *Space = isl_map_get_space(Relation);
1290           Space = isl_space_range(Space);
1291           Space = isl_space_from_range(Space);
1292           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1293           isl_map *Universe = isl_map_universe(Space);
1294           Relation = isl_map_domain_product(Relation, Universe);
1295           Accesses = isl_union_map_add_map(Accesses, Relation);
1296         }
1297 
1298     return Accesses;
1299   }
1300 
1301   /// Get the set of all read accesses, tagged with the access id.
1302   ///
1303   /// @see getTaggedAccesses
1304   isl_union_map *getTaggedReads() {
1305     return getTaggedAccesses(MemoryAccess::READ);
1306   }
1307 
1308   /// Get the set of all may (and must) accesses, tagged with the access id.
1309   ///
1310   /// @see getTaggedAccesses
1311   isl_union_map *getTaggedMayWrites() {
1312     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1313                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1314   }
1315 
1316   /// Get the set of all must accesses, tagged with the access id.
1317   ///
1318   /// @see getTaggedAccesses
1319   isl_union_map *getTaggedMustWrites() {
1320     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1321   }
1322 
1323   /// Collect parameter and array names as isl_ids.
1324   ///
1325   /// To reason about the different parameters and arrays used, ppcg requires
1326   /// a list of all isl_ids in use. As PPCG traditionally performs
1327   /// source-to-source compilation each of these isl_ids is mapped to the
1328   /// expression that represents it. As we do not have a corresponding
1329   /// expression in Polly, we just map each id to a 'zero' expression to match
1330   /// the data format that ppcg expects.
1331   ///
1332   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1333   __isl_give isl_id_to_ast_expr *getNames() {
1334     auto *Names = isl_id_to_ast_expr_alloc(
1335         S->getIslCtx(),
1336         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1337     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1338     auto *Space = S->getParamSpace();
1339 
1340     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1341       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1342       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1343     }
1344 
1345     for (auto &Array : S->arrays()) {
1346       auto Id = Array.second->getBasePtrId();
1347       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1348     }
1349 
1350     isl_space_free(Space);
1351     isl_ast_expr_free(Zero);
1352 
1353     return Names;
1354   }
1355 
1356   /// Create a new PPCG scop from the current scop.
1357   ///
1358   /// The PPCG scop is initialized with data from the current polly::Scop. From
1359   /// this initial data, the data-dependences in the PPCG scop are initialized.
1360   /// We do not use Polly's dependence analysis for now, to ensure we match
1361   /// the PPCG default behaviour more closely.
1362   ///
1363   /// @returns A new ppcg scop.
1364   ppcg_scop *createPPCGScop() {
1365     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1366 
1367     PPCGScop->options = createPPCGOptions();
1368 
1369     PPCGScop->start = 0;
1370     PPCGScop->end = 0;
1371 
1372     PPCGScop->context = S->getContext();
1373     PPCGScop->domain = S->getDomains();
1374     PPCGScop->call = nullptr;
1375     PPCGScop->tagged_reads = getTaggedReads();
1376     PPCGScop->reads = S->getReads();
1377     PPCGScop->live_in = nullptr;
1378     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1379     PPCGScop->may_writes = S->getWrites();
1380     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1381     PPCGScop->must_writes = S->getMustWrites();
1382     PPCGScop->live_out = nullptr;
1383     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1384     PPCGScop->tagger = nullptr;
1385 
1386     PPCGScop->independence = nullptr;
1387     PPCGScop->dep_flow = nullptr;
1388     PPCGScop->tagged_dep_flow = nullptr;
1389     PPCGScop->dep_false = nullptr;
1390     PPCGScop->dep_forced = nullptr;
1391     PPCGScop->dep_order = nullptr;
1392     PPCGScop->tagged_dep_order = nullptr;
1393 
1394     PPCGScop->schedule = S->getScheduleTree();
1395     PPCGScop->names = getNames();
1396 
1397     PPCGScop->pet = nullptr;
1398 
1399     compute_tagger(PPCGScop);
1400     compute_dependences(PPCGScop);
1401 
1402     return PPCGScop;
1403   }
1404 
1405   /// Collect the array acesses in a statement.
1406   ///
1407   /// @param Stmt The statement for which to collect the accesses.
1408   ///
1409   /// @returns A list of array accesses.
1410   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
1411     gpu_stmt_access *Accesses = nullptr;
1412 
1413     for (MemoryAccess *Acc : Stmt) {
1414       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
1415       Access->read = Acc->isRead();
1416       Access->write = Acc->isWrite();
1417       Access->access = Acc->getAccessRelation();
1418       isl_space *Space = isl_map_get_space(Access->access);
1419       Space = isl_space_range(Space);
1420       Space = isl_space_from_range(Space);
1421       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1422       isl_map *Universe = isl_map_universe(Space);
1423       Access->tagged_access =
1424           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1425       Access->exact_write = Acc->isWrite();
1426       Access->ref_id = Acc->getId();
1427       Access->next = Accesses;
1428       Accesses = Access;
1429     }
1430 
1431     return Accesses;
1432   }
1433 
1434   /// Collect the list of GPU statements.
1435   ///
1436   /// Each statement has an id, a pointer to the underlying data structure,
1437   /// as well as a list with all memory accesses.
1438   ///
1439   /// TODO: Initialize the list of memory accesses.
1440   ///
1441   /// @returns A linked-list of statements.
1442   gpu_stmt *getStatements() {
1443     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
1444                                        std::distance(S->begin(), S->end()));
1445 
1446     int i = 0;
1447     for (auto &Stmt : *S) {
1448       gpu_stmt *GPUStmt = &Stmts[i];
1449 
1450       GPUStmt->id = Stmt.getDomainId();
1451 
1452       // We use the pet stmt pointer to keep track of the Polly statements.
1453       GPUStmt->stmt = (pet_stmt *)&Stmt;
1454       GPUStmt->accesses = getStmtAccesses(Stmt);
1455       i++;
1456     }
1457 
1458     return Stmts;
1459   }
1460 
1461   /// Derive the extent of an array.
1462   ///
1463   /// The extent of an array is defined by the set of memory locations for
1464   /// which a memory access in the iteration domain exists.
1465   ///
1466   /// @param Array The array to derive the extent for.
1467   ///
1468   /// @returns An isl_set describing the extent of the array.
1469   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1470     isl_union_map *Accesses = S->getAccesses();
1471     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1472     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1473     isl_set *AccessSet =
1474         isl_union_set_extract_set(AccessUSet, Array->getSpace());
1475     isl_union_set_free(AccessUSet);
1476 
1477     return AccessSet;
1478   }
1479 
1480   /// Derive the bounds of an array.
1481   ///
1482   /// For the first dimension we derive the bound of the array from the extent
1483   /// of this dimension. For inner dimensions we obtain their size directly from
1484   /// ScopArrayInfo.
1485   ///
1486   /// @param PPCGArray The array to compute bounds for.
1487   /// @param Array The polly array from which to take the information.
1488   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
1489     if (PPCGArray.n_index > 0) {
1490       isl_set *Dom = isl_set_copy(PPCGArray.extent);
1491       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
1492       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
1493       isl_set_free(Dom);
1494       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
1495       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
1496       isl_aff *One = isl_aff_zero_on_domain(LS);
1497       One = isl_aff_add_constant_si(One, 1);
1498       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
1499       Bound = isl_pw_aff_gist(Bound, S->getContext());
1500       PPCGArray.bound[0] = Bound;
1501     }
1502 
1503     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
1504       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
1505       auto LS = isl_pw_aff_get_domain_space(Bound);
1506       auto Aff = isl_multi_aff_zero(LS);
1507       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
1508       PPCGArray.bound[i] = Bound;
1509     }
1510   }
1511 
1512   /// Create the arrays for @p PPCGProg.
1513   ///
1514   /// @param PPCGProg The program to compute the arrays for.
1515   void createArrays(gpu_prog *PPCGProg) {
1516     int i = 0;
1517     for (auto &Element : S->arrays()) {
1518       ScopArrayInfo *Array = Element.second.get();
1519 
1520       std::string TypeName;
1521       raw_string_ostream OS(TypeName);
1522 
1523       OS << *Array->getElementType();
1524       TypeName = OS.str();
1525 
1526       gpu_array_info &PPCGArray = PPCGProg->array[i];
1527 
1528       PPCGArray.space = Array->getSpace();
1529       PPCGArray.type = strdup(TypeName.c_str());
1530       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
1531       PPCGArray.name = strdup(Array->getName().c_str());
1532       PPCGArray.extent = nullptr;
1533       PPCGArray.n_index = Array->getNumberOfDimensions();
1534       PPCGArray.bound =
1535           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
1536       PPCGArray.extent = getExtent(Array);
1537       PPCGArray.n_ref = 0;
1538       PPCGArray.refs = nullptr;
1539       PPCGArray.accessed = true;
1540       PPCGArray.read_only_scalar = false;
1541       PPCGArray.has_compound_element = false;
1542       PPCGArray.local = false;
1543       PPCGArray.declare_local = false;
1544       PPCGArray.global = false;
1545       PPCGArray.linearize = false;
1546       PPCGArray.dep_order = nullptr;
1547       PPCGArray.user = Array;
1548 
1549       setArrayBounds(PPCGArray, Array);
1550       i++;
1551 
1552       collect_references(PPCGProg, &PPCGArray);
1553     }
1554   }
1555 
1556   /// Create an identity map between the arrays in the scop.
1557   ///
1558   /// @returns An identity map between the arrays in the scop.
1559   isl_union_map *getArrayIdentity() {
1560     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
1561 
1562     for (auto &Item : S->arrays()) {
1563       ScopArrayInfo *Array = Item.second.get();
1564       isl_space *Space = Array->getSpace();
1565       Space = isl_space_map_from_set(Space);
1566       isl_map *Identity = isl_map_identity(Space);
1567       Maps = isl_union_map_add_map(Maps, Identity);
1568     }
1569 
1570     return Maps;
1571   }
1572 
1573   /// Create a default-initialized PPCG GPU program.
1574   ///
1575   /// @returns A new gpu grogram description.
1576   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1577 
1578     if (!PPCGScop)
1579       return nullptr;
1580 
1581     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1582 
1583     PPCGProg->ctx = S->getIslCtx();
1584     PPCGProg->scop = PPCGScop;
1585     PPCGProg->context = isl_set_copy(PPCGScop->context);
1586     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
1587     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
1588     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
1589     PPCGProg->tagged_must_kill =
1590         isl_union_map_copy(PPCGScop->tagged_must_kills);
1591     PPCGProg->to_inner = getArrayIdentity();
1592     PPCGProg->to_outer = getArrayIdentity();
1593     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1594     PPCGProg->any_to_outer = nullptr;
1595     PPCGProg->array_order = nullptr;
1596     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
1597     PPCGProg->stmts = getStatements();
1598     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
1599     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
1600                                        PPCGProg->n_array);
1601 
1602     createArrays(PPCGProg);
1603 
1604     return PPCGProg;
1605   }
1606 
1607   struct PrintGPUUserData {
1608     struct cuda_info *CudaInfo;
1609     struct gpu_prog *PPCGProg;
1610     std::vector<ppcg_kernel *> Kernels;
1611   };
1612 
1613   /// Print a user statement node in the host code.
1614   ///
1615   /// We use ppcg's printing facilities to print the actual statement and
1616   /// additionally build up a list of all kernels that are encountered in the
1617   /// host ast.
1618   ///
1619   /// @param P The printer to print to
1620   /// @param Options The printing options to use
1621   /// @param Node The node to print
1622   /// @param User A user pointer to carry additional data. This pointer is
1623   ///             expected to be of type PrintGPUUserData.
1624   ///
1625   /// @returns A printer to which the output has been printed.
1626   static __isl_give isl_printer *
1627   printHostUser(__isl_take isl_printer *P,
1628                 __isl_take isl_ast_print_options *Options,
1629                 __isl_take isl_ast_node *Node, void *User) {
1630     auto Data = (struct PrintGPUUserData *)User;
1631     auto Id = isl_ast_node_get_annotation(Node);
1632 
1633     if (Id) {
1634       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
1635 
1636       // If this is a user statement, format it ourselves as ppcg would
1637       // otherwise try to call pet functionality that is not available in
1638       // Polly.
1639       if (IsUser) {
1640         P = isl_printer_start_line(P);
1641         P = isl_printer_print_ast_node(P, Node);
1642         P = isl_printer_end_line(P);
1643         isl_id_free(Id);
1644         isl_ast_print_options_free(Options);
1645         return P;
1646       }
1647 
1648       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
1649       isl_id_free(Id);
1650       Data->Kernels.push_back(Kernel);
1651     }
1652 
1653     return print_host_user(P, Options, Node, User);
1654   }
1655 
1656   /// Print C code corresponding to the control flow in @p Kernel.
1657   ///
1658   /// @param Kernel The kernel to print
1659   void printKernel(ppcg_kernel *Kernel) {
1660     auto *P = isl_printer_to_str(S->getIslCtx());
1661     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1662     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1663     P = isl_ast_node_print(Kernel->tree, P, Options);
1664     char *String = isl_printer_get_str(P);
1665     printf("%s\n", String);
1666     free(String);
1667     isl_printer_free(P);
1668   }
1669 
1670   /// Print C code corresponding to the GPU code described by @p Tree.
1671   ///
1672   /// @param Tree An AST describing GPU code
1673   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
1674   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
1675     auto *P = isl_printer_to_str(S->getIslCtx());
1676     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
1677 
1678     PrintGPUUserData Data;
1679     Data.PPCGProg = PPCGProg;
1680 
1681     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
1682     Options =
1683         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
1684     P = isl_ast_node_print(Tree, P, Options);
1685     char *String = isl_printer_get_str(P);
1686     printf("# host\n");
1687     printf("%s\n", String);
1688     free(String);
1689     isl_printer_free(P);
1690 
1691     for (auto Kernel : Data.Kernels) {
1692       printf("# kernel%d\n", Kernel->id);
1693       printKernel(Kernel);
1694     }
1695   }
1696 
1697   // Generate a GPU program using PPCG.
1698   //
1699   // GPU mapping consists of multiple steps:
1700   //
1701   //  1) Compute new schedule for the program.
1702   //  2) Map schedule to GPU (TODO)
1703   //  3) Generate code for new schedule (TODO)
1704   //
1705   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1706   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1707   // strategy directly from this pass.
1708   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1709 
1710     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1711 
1712     PPCGGen->ctx = S->getIslCtx();
1713     PPCGGen->options = PPCGScop->options;
1714     PPCGGen->print = nullptr;
1715     PPCGGen->print_user = nullptr;
1716     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1717     PPCGGen->prog = PPCGProg;
1718     PPCGGen->tree = nullptr;
1719     PPCGGen->types.n = 0;
1720     PPCGGen->types.name = nullptr;
1721     PPCGGen->sizes = nullptr;
1722     PPCGGen->used_sizes = nullptr;
1723     PPCGGen->kernel_id = 0;
1724 
1725     // Set scheduling strategy to same strategy PPCG is using.
1726     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1727     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
1728     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1729 
1730     isl_schedule *Schedule = get_schedule(PPCGGen);
1731 
1732     int has_permutable = has_any_permutable_node(Schedule);
1733 
1734     if (!has_permutable || has_permutable < 0) {
1735       Schedule = isl_schedule_free(Schedule);
1736     } else {
1737       Schedule = map_to_device(PPCGGen, Schedule);
1738       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
1739     }
1740 
1741     if (DumpSchedule) {
1742       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1743       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1744       P = isl_printer_print_str(P, "Schedule\n");
1745       P = isl_printer_print_str(P, "========\n");
1746       if (Schedule)
1747         P = isl_printer_print_schedule(P, Schedule);
1748       else
1749         P = isl_printer_print_str(P, "No schedule found\n");
1750 
1751       printf("%s\n", isl_printer_get_str(P));
1752       isl_printer_free(P);
1753     }
1754 
1755     if (DumpCode) {
1756       printf("Code\n");
1757       printf("====\n");
1758       if (PPCGGen->tree)
1759         printGPUTree(PPCGGen->tree, PPCGProg);
1760       else
1761         printf("No code generated\n");
1762     }
1763 
1764     isl_schedule_free(Schedule);
1765 
1766     return PPCGGen;
1767   }
1768 
1769   /// Free gpu_gen structure.
1770   ///
1771   /// @param PPCGGen The ppcg_gen object to free.
1772   void freePPCGGen(gpu_gen *PPCGGen) {
1773     isl_ast_node_free(PPCGGen->tree);
1774     isl_union_map_free(PPCGGen->sizes);
1775     isl_union_map_free(PPCGGen->used_sizes);
1776     free(PPCGGen);
1777   }
1778 
1779   /// Free the options in the ppcg scop structure.
1780   ///
1781   /// ppcg is not freeing these options for us. To avoid leaks we do this
1782   /// ourselves.
1783   ///
1784   /// @param PPCGScop The scop referencing the options to free.
1785   void freeOptions(ppcg_scop *PPCGScop) {
1786     free(PPCGScop->options->debug);
1787     PPCGScop->options->debug = nullptr;
1788     free(PPCGScop->options);
1789     PPCGScop->options = nullptr;
1790   }
1791 
1792   /// Generate code for a given GPU AST described by @p Root.
1793   ///
1794   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
1795   /// @param Prog The GPU Program to generate code for.
1796   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
1797     ScopAnnotator Annotator;
1798     Annotator.buildAliasScopes(*S);
1799 
1800     Region *R = &S->getRegion();
1801 
1802     simplifyRegion(R, DT, LI, RI);
1803 
1804     BasicBlock *EnteringBB = R->getEnteringBlock();
1805 
1806     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
1807 
1808     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
1809                                Prog);
1810 
1811     // Only build the run-time condition and parameters _after_ having
1812     // introduced the conditional branch. This is important as the conditional
1813     // branch will guard the original scop from new induction variables that
1814     // the SCEVExpander may introduce while code generating the parameters and
1815     // which may introduce scalar dependences that prevent us from correctly
1816     // code generating this scop.
1817     BasicBlock *StartBlock =
1818         executeScopConditionally(*S, this, Builder.getTrue());
1819 
1820     // TODO: Handle LICM
1821     // TODO: Verify run-time checks
1822     auto SplitBlock = StartBlock->getSinglePredecessor();
1823     Builder.SetInsertPoint(SplitBlock->getTerminator());
1824     NodeBuilder.addParameters(S->getContext());
1825     Builder.SetInsertPoint(&*StartBlock->begin());
1826 
1827     NodeBuilder.initializeAfterRTH();
1828     NodeBuilder.create(Root);
1829     NodeBuilder.finalize();
1830   }
1831 
1832   bool runOnScop(Scop &CurrentScop) override {
1833     S = &CurrentScop;
1834     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1835     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1836     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1837     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
1838     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1839 
1840     // We currently do not support scops with invariant loads.
1841     if (S->hasInvariantAccesses())
1842       return false;
1843 
1844     auto PPCGScop = createPPCGScop();
1845     auto PPCGProg = createPPCGProg(PPCGScop);
1846     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
1847 
1848     if (PPCGGen->tree)
1849       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
1850 
1851     freeOptions(PPCGScop);
1852     freePPCGGen(PPCGGen);
1853     gpu_prog_free(PPCGProg);
1854     ppcg_scop_free(PPCGScop);
1855 
1856     return true;
1857   }
1858 
1859   void printScop(raw_ostream &, Scop &) const override {}
1860 
1861   void getAnalysisUsage(AnalysisUsage &AU) const override {
1862     AU.addRequired<DominatorTreeWrapperPass>();
1863     AU.addRequired<RegionInfoPass>();
1864     AU.addRequired<ScalarEvolutionWrapperPass>();
1865     AU.addRequired<ScopDetection>();
1866     AU.addRequired<ScopInfoRegionPass>();
1867     AU.addRequired<LoopInfoWrapperPass>();
1868 
1869     AU.addPreserved<AAResultsWrapperPass>();
1870     AU.addPreserved<BasicAAWrapperPass>();
1871     AU.addPreserved<LoopInfoWrapperPass>();
1872     AU.addPreserved<DominatorTreeWrapperPass>();
1873     AU.addPreserved<GlobalsAAWrapperPass>();
1874     AU.addPreserved<PostDominatorTreeWrapperPass>();
1875     AU.addPreserved<ScopDetection>();
1876     AU.addPreserved<ScalarEvolutionWrapperPass>();
1877     AU.addPreserved<SCEVAAWrapperPass>();
1878 
1879     // FIXME: We do not yet add regions for the newly generated code to the
1880     //        region tree.
1881     AU.addPreserved<RegionInfoPass>();
1882     AU.addPreserved<ScopInfoRegionPass>();
1883   }
1884 };
1885 }
1886 
1887 char PPCGCodeGeneration::ID = 1;
1888 
1889 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
1890 
1891 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
1892                       "Polly - Apply PPCG translation to SCOP", false, false)
1893 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
1894 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1895 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1896 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1897 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1898 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1899 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
1900                     "Polly - Apply PPCG translation to SCOP", false, false)
1901