19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
20629109b6STobias Grosser #include "polly/ScopDetection.h"
219dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
22edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2374dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3174dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
32e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3574dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
369a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
379dfe4e7cSTobias Grosser 
38f384594dSTobias Grosser #include "isl/union_map.h"
39f384594dSTobias Grosser 
40e938517eSTobias Grosser extern "C" {
41a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
42a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
43a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
44a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
45a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
46e938517eSTobias Grosser }
47e938517eSTobias Grosser 
489dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
499dfe4e7cSTobias Grosser 
509dfe4e7cSTobias Grosser using namespace polly;
519dfe4e7cSTobias Grosser using namespace llvm;
529dfe4e7cSTobias Grosser 
539dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
549dfe4e7cSTobias Grosser 
55f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
56f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
57681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
58f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5969b46751STobias Grosser 
6069b46751STobias Grosser static cl::opt<bool>
6169b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6269b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6369b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6469b46751STobias Grosser 
6532837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6632837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6732837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6832837fe3STobias Grosser                                   cl::cat(PollyCategory));
6932837fe3STobias Grosser 
7074dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7174dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7274dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7374dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7474dc3cb4STobias Grosser 
7574dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7674dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7774dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7874dc3cb4STobias Grosser                               cl::cat(PollyCategory));
7974dc3cb4STobias Grosser 
8074dc3cb4STobias Grosser static cl::opt<std::string>
8174dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
8274dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
8374dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
8474dc3cb4STobias Grosser 
8560c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
8660c60025STobias Grosser ///
8760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
8860c60025STobias Grosser /// of the scheduled ScopStmts.
8960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
90edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
9160c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
9260c60025STobias Grosser                                        isl_id *Id, void *User),
9360c60025STobias Grosser     void *UserIndex,
9460c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
95edb885cbSTobias Grosser     void *UserExpr) {
9660c60025STobias Grosser 
97edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
9860c60025STobias Grosser 
99edb885cbSTobias Grosser   isl_ctx *Ctx;
100edb885cbSTobias Grosser 
101edb885cbSTobias Grosser   if (!Stmt || !Build)
102edb885cbSTobias Grosser     return NULL;
103edb885cbSTobias Grosser 
104edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
105edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
106edb885cbSTobias Grosser 
107edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
108edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
109edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
110edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
111edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
112edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
113edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
114edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
115edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
116edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
117edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
118edb885cbSTobias Grosser   }
119edb885cbSTobias Grosser 
120edb885cbSTobias Grosser   return RefToExpr;
12160c60025STobias Grosser }
122f384594dSTobias Grosser 
12338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
12438fc0aedSTobias Grosser ///
12538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
12638fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
12738fc0aedSTobias Grosser /// for generating GPU specific user nodes.
12838fc0aedSTobias Grosser ///
12938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
13038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
13138fc0aedSTobias Grosser public:
13238fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
13338fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
13432837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
135edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
136edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
137edb885cbSTobias Grosser   }
13838fc0aedSTobias Grosser 
139fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
140fa7b0802STobias Grosser   void initializeAfterRTH();
141fa7b0802STobias Grosser 
142fa7b0802STobias Grosser   /// Finalize the generated scop.
143fa7b0802STobias Grosser   virtual void finalize();
144fa7b0802STobias Grosser 
14538fc0aedSTobias Grosser private:
14674dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
14774dc3cb4STobias Grosser   ///
14874dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
14974dc3cb4STobias Grosser   /// more.
15074dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
15174dc3cb4STobias Grosser 
15213c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
15313c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1547287aeddSTobias Grosser 
155fa7b0802STobias Grosser   /// The current GPU context.
156fa7b0802STobias Grosser   Value *GPUContext;
157fa7b0802STobias Grosser 
15832837fe3STobias Grosser   /// A module containing GPU code.
15932837fe3STobias Grosser   ///
16032837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
16132837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
16232837fe3STobias Grosser 
16332837fe3STobias Grosser   /// The GPU program we generate code for.
16432837fe3STobias Grosser   gpu_prog *Prog;
16532837fe3STobias Grosser 
166472f9654STobias Grosser   /// Class to free isl_ids.
167472f9654STobias Grosser   class IslIdDeleter {
168472f9654STobias Grosser   public:
169472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
170472f9654STobias Grosser   };
171472f9654STobias Grosser 
172472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
173472f9654STobias Grosser   ///
174472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
175472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
176472f9654STobias Grosser 
177edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
178edb885cbSTobias Grosser 
17938fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
18038fc0aedSTobias Grosser   ///
18138fc0aedSTobias Grosser   /// These AST nodes can be of type:
18238fc0aedSTobias Grosser   ///
18338fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
18438fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
18513c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1865260c041STobias Grosser   ///   - In-kernel synchronization
1875260c041STobias Grosser   ///   - In-kernel memory copy statement
18838fc0aedSTobias Grosser   ///
1891fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1901fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
19132837fe3STobias Grosser 
19213c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
19313c78e4dSTobias Grosser 
19413c78e4dSTobias Grosser   /// Create code for a data transfer statement
19513c78e4dSTobias Grosser   ///
19613c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
19713c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
19813c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
19913c78e4dSTobias Grosser                           enum DataDirection Direction);
20013c78e4dSTobias Grosser 
201edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
202edb885cbSTobias Grosser   ///
203edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
204edb885cbSTobias Grosser   ///
205edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
206edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
207edb885cbSTobias Grosser 
20879a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
20979a947c2STobias Grosser   ///
21079a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
21179a947c2STobias Grosser   ///
21279a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
21379a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
21479a947c2STobias Grosser 
21579a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
21679a947c2STobias Grosser   ///
21779a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
21879a947c2STobias Grosser   ///
21979a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
22079a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
22179a947c2STobias Grosser 
22279a947c2STobias Grosser   /// Create kernel launch parameters.
22379a947c2STobias Grosser   ///
22479a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
22579a947c2STobias Grosser   /// @param F             The kernel function that has been created.
22657693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
22779a947c2STobias Grosser   ///
22879a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
22979a947c2STobias Grosser   ///          values that are passed to the kernel.
23057693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
23157693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
23279a947c2STobias Grosser 
23332837fe3STobias Grosser   /// Create GPU kernel.
23432837fe3STobias Grosser   ///
23532837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
23632837fe3STobias Grosser   ///
23732837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
23832837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
23932837fe3STobias Grosser 
24013c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
24113c78e4dSTobias Grosser   ///
24213c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
24313c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
24413c78e4dSTobias Grosser 
245*00bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
246*00bb5a99STobias Grosser   ///
247*00bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
248*00bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
249*00bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
250*00bb5a99STobias Grosser 
25132837fe3STobias Grosser   /// Create kernel function.
25232837fe3STobias Grosser   ///
25332837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
25432837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
25532837fe3STobias Grosser   /// start block of this newly created function.
25632837fe3STobias Grosser   ///
25732837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
258edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
259edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
260edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
26132837fe3STobias Grosser 
26232837fe3STobias Grosser   /// Create the declaration of a kernel function.
26332837fe3STobias Grosser   ///
26432837fe3STobias Grosser   /// The kernel function takes as arguments:
26532837fe3STobias Grosser   ///
26632837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
267f6044bd0STobias Grosser   ///   - Host iterators
268c84a1995STobias Grosser   ///   - Parameters
26932837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
27032837fe3STobias Grosser   ///
27132837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
272edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
273edb885cbSTobias Grosser   ///
27432837fe3STobias Grosser   /// @returns The newly declared function.
275edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
276edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
27732837fe3STobias Grosser 
278472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
279472f9654STobias Grosser   ///
280472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
281472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
282472f9654STobias Grosser 
283edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
284edb885cbSTobias Grosser   ///
285edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
286edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
287edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
288edb885cbSTobias Grosser 
2895260c041STobias Grosser   /// Create an in-kernel synchronization call.
2905260c041STobias Grosser   void createKernelSync();
2915260c041STobias Grosser 
29274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
29374dc3cb4STobias Grosser   ///
29474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
29574dc3cb4STobias Grosser   std::string createKernelASM();
29674dc3cb4STobias Grosser 
29774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
29874dc3cb4STobias Grosser   ///
29974dc3cb4STobias Grosser   /// @param F The function to remove references to.
30074dc3cb4STobias Grosser   void clearDominators(Function *F);
30174dc3cb4STobias Grosser 
30274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
30374dc3cb4STobias Grosser   ///
30474dc3cb4STobias Grosser   /// @param F The function to remove references to.
30574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
30674dc3cb4STobias Grosser 
30774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
30874dc3cb4STobias Grosser   ///
30974dc3cb4STobias Grosser   /// @param F The function to remove references to.
31074dc3cb4STobias Grosser   void clearLoops(Function *F);
31174dc3cb4STobias Grosser 
31232837fe3STobias Grosser   /// Finalize the generation of the kernel function.
31332837fe3STobias Grosser   ///
31432837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
31532837fe3STobias Grosser   /// dump its IR to stderr.
31657793596STobias Grosser   ///
31757793596STobias Grosser   /// @returns The Assembly string of the kernel.
31857793596STobias Grosser   std::string finalizeKernelFunction();
319fa7b0802STobias Grosser 
3207287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
321fa7b0802STobias Grosser   void allocateDeviceArrays();
322fa7b0802STobias Grosser 
3237287aeddSTobias Grosser   /// Free all allocated device arrays.
3247287aeddSTobias Grosser   void freeDeviceArrays();
3257287aeddSTobias Grosser 
326fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
327fa7b0802STobias Grosser   ///
328fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
329fa7b0802STobias Grosser   Value *createCallInitContext();
330fa7b0802STobias Grosser 
33179a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
33279a947c2STobias Grosser   ///
33379a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
33479a947c2STobias Grosser   ///
33579a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
33679a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
33779a947c2STobias Grosser 
338fa7b0802STobias Grosser   /// Create a call to free the GPU context.
339fa7b0802STobias Grosser   ///
340fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
341fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
342fa7b0802STobias Grosser 
3437287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3447287aeddSTobias Grosser   ///
3457287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3467287aeddSTobias Grosser   ///
3477287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
348fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3497287aeddSTobias Grosser 
3507287aeddSTobias Grosser   /// Create a call to free a device array.
3517287aeddSTobias Grosser   ///
3527287aeddSTobias Grosser   /// @param Array The device array to free.
3537287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
35413c78e4dSTobias Grosser 
35513c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
35613c78e4dSTobias Grosser   ///
35713c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
35813c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
35913c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
36013c78e4dSTobias Grosser                                       Value *Size);
36113c78e4dSTobias Grosser 
36213c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
36313c78e4dSTobias Grosser   ///
36413c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
36513c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
36613c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
36713c78e4dSTobias Grosser                                       Value *Size);
36857793596STobias Grosser 
36957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
37057793596STobias Grosser   ///
37157793596STobias Grosser   /// @param Buffer The string describing the kernel.
37257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
37357793596STobias Grosser   ///
37457793596STobias Grosser   /// @returns A pointer to a kernel object
37557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
37657793596STobias Grosser 
37757793596STobias Grosser   /// Create a call to free a GPU kernel.
37857793596STobias Grosser   ///
37957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
38057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
38179a947c2STobias Grosser 
38279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
38379a947c2STobias Grosser   ///
38479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
38579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
38679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
38779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
38879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
38979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
39079a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
39179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
39279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
39379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
39479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
39579a947c2STobias Grosser                               Value *Parameters);
3961fb9b64dSTobias Grosser };
3971fb9b64dSTobias Grosser 
398fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
399fa7b0802STobias Grosser   GPUContext = createCallInitContext();
400fa7b0802STobias Grosser   allocateDeviceArrays();
401fa7b0802STobias Grosser }
402fa7b0802STobias Grosser 
403fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4047287aeddSTobias Grosser   freeDeviceArrays();
405fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
406fa7b0802STobias Grosser   IslNodeBuilder::finalize();
407fa7b0802STobias Grosser }
408fa7b0802STobias Grosser 
409fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
410fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
411fa7b0802STobias Grosser 
412fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
413fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
41413c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4157287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4167287aeddSTobias Grosser     DevArrayName.append(Array->name);
417fa7b0802STobias Grosser 
41813c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
4197287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4207287aeddSTobias Grosser     DevArray->setName(DevArrayName);
42113c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
422fa7b0802STobias Grosser   }
423fa7b0802STobias Grosser 
424fa7b0802STobias Grosser   isl_ast_build_free(Build);
425fa7b0802STobias Grosser }
426fa7b0802STobias Grosser 
4277287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
42813c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
42913c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
4307287aeddSTobias Grosser }
4317287aeddSTobias Grosser 
43257793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
43357793596STobias Grosser   const char *Name = "polly_getKernel";
43457793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
43557793596STobias Grosser   Function *F = M->getFunction(Name);
43657793596STobias Grosser 
43757793596STobias Grosser   // If F is not available, declare it.
43857793596STobias Grosser   if (!F) {
43957793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
44057793596STobias Grosser     std::vector<Type *> Args;
44157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
44257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
44357793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
44457793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
44557793596STobias Grosser   }
44657793596STobias Grosser 
44757793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
44857793596STobias Grosser }
44957793596STobias Grosser 
45079a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
45179a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
45279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
45379a947c2STobias Grosser   Function *F = M->getFunction(Name);
45479a947c2STobias Grosser 
45579a947c2STobias Grosser   // If F is not available, declare it.
45679a947c2STobias Grosser   if (!F) {
45779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
45879a947c2STobias Grosser     std::vector<Type *> Args;
45979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
46079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
46179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
46279a947c2STobias Grosser   }
46379a947c2STobias Grosser 
46479a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
46579a947c2STobias Grosser }
46679a947c2STobias Grosser 
46779a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
46879a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
46979a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
47079a947c2STobias Grosser                                             Value *Parameters) {
47179a947c2STobias Grosser   const char *Name = "polly_launchKernel";
47279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
47379a947c2STobias Grosser   Function *F = M->getFunction(Name);
47479a947c2STobias Grosser 
47579a947c2STobias Grosser   // If F is not available, declare it.
47679a947c2STobias Grosser   if (!F) {
47779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
47879a947c2STobias Grosser     std::vector<Type *> Args;
47979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
48079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
48179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
48279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
48379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
48479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
48579a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
48679a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
48779a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
48879a947c2STobias Grosser   }
48979a947c2STobias Grosser 
49079a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
49179a947c2STobias Grosser                          BlockDimZ, Parameters});
49279a947c2STobias Grosser }
49379a947c2STobias Grosser 
49457793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
49557793596STobias Grosser   const char *Name = "polly_freeKernel";
49657793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
49757793596STobias Grosser   Function *F = M->getFunction(Name);
49857793596STobias Grosser 
49957793596STobias Grosser   // If F is not available, declare it.
50057793596STobias Grosser   if (!F) {
50157793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
50257793596STobias Grosser     std::vector<Type *> Args;
50357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
50457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
50557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
50657793596STobias Grosser   }
50757793596STobias Grosser 
50857793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
50957793596STobias Grosser }
51057793596STobias Grosser 
5117287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
5127287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
5137287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
5147287aeddSTobias Grosser   Function *F = M->getFunction(Name);
5157287aeddSTobias Grosser 
5167287aeddSTobias Grosser   // If F is not available, declare it.
5177287aeddSTobias Grosser   if (!F) {
5187287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
5197287aeddSTobias Grosser     std::vector<Type *> Args;
5207287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
5217287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
5227287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
5237287aeddSTobias Grosser   }
5247287aeddSTobias Grosser 
5257287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
5267287aeddSTobias Grosser }
5277287aeddSTobias Grosser 
528fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
529fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
530fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
531fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
532fa7b0802STobias Grosser 
533fa7b0802STobias Grosser   // If F is not available, declare it.
534fa7b0802STobias Grosser   if (!F) {
535fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
536fa7b0802STobias Grosser     std::vector<Type *> Args;
537fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
538fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
539fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
540fa7b0802STobias Grosser   }
541fa7b0802STobias Grosser 
542fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
543fa7b0802STobias Grosser }
544fa7b0802STobias Grosser 
54513c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
54613c78e4dSTobias Grosser                                                     Value *DeviceData,
54713c78e4dSTobias Grosser                                                     Value *Size) {
54813c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
54913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
55013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
55113c78e4dSTobias Grosser 
55213c78e4dSTobias Grosser   // If F is not available, declare it.
55313c78e4dSTobias Grosser   if (!F) {
55413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
55513c78e4dSTobias Grosser     std::vector<Type *> Args;
55613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
55913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
56013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
56113c78e4dSTobias Grosser   }
56213c78e4dSTobias Grosser 
56313c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
56413c78e4dSTobias Grosser }
56513c78e4dSTobias Grosser 
56613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
56713c78e4dSTobias Grosser                                                     Value *HostData,
56813c78e4dSTobias Grosser                                                     Value *Size) {
56913c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
57013c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
57113c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
57213c78e4dSTobias Grosser 
57313c78e4dSTobias Grosser   // If F is not available, declare it.
57413c78e4dSTobias Grosser   if (!F) {
57513c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57613c78e4dSTobias Grosser     std::vector<Type *> Args;
57713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57913c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
58013c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
58113c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
58213c78e4dSTobias Grosser   }
58313c78e4dSTobias Grosser 
58413c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
58513c78e4dSTobias Grosser }
58613c78e4dSTobias Grosser 
587fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
588fa7b0802STobias Grosser   const char *Name = "polly_initContext";
589fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
590fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
591fa7b0802STobias Grosser 
592fa7b0802STobias Grosser   // If F is not available, declare it.
593fa7b0802STobias Grosser   if (!F) {
594fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
595fa7b0802STobias Grosser     std::vector<Type *> Args;
596fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
597fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
598fa7b0802STobias Grosser   }
599fa7b0802STobias Grosser 
600fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
601fa7b0802STobias Grosser }
602fa7b0802STobias Grosser 
603fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
604fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
605fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
606fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
607fa7b0802STobias Grosser 
608fa7b0802STobias Grosser   // If F is not available, declare it.
609fa7b0802STobias Grosser   if (!F) {
610fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
611fa7b0802STobias Grosser     std::vector<Type *> Args;
612fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
613fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
614fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
615fa7b0802STobias Grosser   }
616fa7b0802STobias Grosser 
617fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
618fa7b0802STobias Grosser }
619fa7b0802STobias Grosser 
6205260c041STobias Grosser /// Check if one string is a prefix of another.
6215260c041STobias Grosser ///
6225260c041STobias Grosser /// @param String The string in which to look for the prefix.
6235260c041STobias Grosser /// @param Prefix The prefix to look for.
6245260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
6255260c041STobias Grosser   return String.find(Prefix) == 0;
6265260c041STobias Grosser }
6275260c041STobias Grosser 
62813c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
62913c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
63013c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
63113c78e4dSTobias Grosser 
63213c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
63313c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
63413c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
63513c78e4dSTobias Grosser 
63613c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
63713c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
63813c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
63913c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
64013c78e4dSTobias Grosser     }
64113c78e4dSTobias Grosser 
64213c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
64313c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
64413c78e4dSTobias Grosser   }
64513c78e4dSTobias Grosser   isl_ast_build_free(Build);
64613c78e4dSTobias Grosser   return ArraySize;
64713c78e4dSTobias Grosser }
64813c78e4dSTobias Grosser 
64913c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
65013c78e4dSTobias Grosser                                         enum DataDirection Direction) {
65113c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
65213c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
65313c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
65413c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
65513c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
65613c78e4dSTobias Grosser 
65713c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
65813c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
66113c78e4dSTobias Grosser 
66213c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
66313c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
66413c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
66513c78e4dSTobias Grosser   }
66613c78e4dSTobias Grosser 
66713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
66813c78e4dSTobias Grosser 
66913c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
67013c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
67113c78e4dSTobias Grosser   else
67213c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
67313c78e4dSTobias Grosser 
67413c78e4dSTobias Grosser   isl_id_free(Id);
67513c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
67613c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
67713c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
67813c78e4dSTobias Grosser }
67913c78e4dSTobias Grosser 
6801fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
68132837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
68232837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
68332837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
68432837fe3STobias Grosser   isl_id_free(Id);
68532837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
68632837fe3STobias Grosser 
68732837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
68832837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
68932837fe3STobias Grosser     createKernel(UserStmt);
69032837fe3STobias Grosser     isl_ast_expr_free(Expr);
69132837fe3STobias Grosser     return;
69232837fe3STobias Grosser   }
69332837fe3STobias Grosser 
69413c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
69513c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
69632837fe3STobias Grosser     isl_ast_expr_free(Expr);
69713c78e4dSTobias Grosser     return;
69813c78e4dSTobias Grosser   }
69913c78e4dSTobias Grosser 
70013c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
70113c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
70213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
70338fc0aedSTobias Grosser     return;
70438fc0aedSTobias Grosser   }
70538fc0aedSTobias Grosser 
7065260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
7075260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
7085260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
7095260c041STobias Grosser   isl_id_free(Anno);
7105260c041STobias Grosser 
7115260c041STobias Grosser   switch (KernelStmt->type) {
7125260c041STobias Grosser   case ppcg_kernel_domain:
713edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
7145260c041STobias Grosser     isl_ast_node_free(UserStmt);
7155260c041STobias Grosser     return;
7165260c041STobias Grosser   case ppcg_kernel_copy:
7175260c041STobias Grosser     // TODO: Create kernel copy stmt
7185260c041STobias Grosser     isl_ast_expr_free(Expr);
7195260c041STobias Grosser     isl_ast_node_free(UserStmt);
7205260c041STobias Grosser     return;
7215260c041STobias Grosser   case ppcg_kernel_sync:
7225260c041STobias Grosser     createKernelSync();
7235260c041STobias Grosser     isl_ast_expr_free(Expr);
7245260c041STobias Grosser     isl_ast_node_free(UserStmt);
7255260c041STobias Grosser     return;
7265260c041STobias Grosser   }
7275260c041STobias Grosser 
7285260c041STobias Grosser   isl_ast_expr_free(Expr);
7295260c041STobias Grosser   isl_ast_node_free(UserStmt);
7305260c041STobias Grosser   return;
7315260c041STobias Grosser }
7325260c041STobias Grosser 
733edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
734edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
735edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
736edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
737edb885cbSTobias Grosser 
738edb885cbSTobias Grosser   LoopToScevMapT LTS;
739edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
740edb885cbSTobias Grosser 
741edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
742edb885cbSTobias Grosser 
743edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
744edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
745edb885cbSTobias Grosser   else
746edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
747edb885cbSTobias Grosser }
748edb885cbSTobias Grosser 
7495260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
7505260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7515260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
7525260c041STobias Grosser   Builder.CreateCall(Sync, {});
7535260c041STobias Grosser }
7545260c041STobias Grosser 
755edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
756edb885cbSTobias Grosser ///
757edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
758edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
759edb885cbSTobias Grosser ///
760edb885cbSTobias Grosser /// @param Node The node to collect references for.
761edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
762edb885cbSTobias Grosser ///
763edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
764edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
765edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
766edb885cbSTobias Grosser     return isl_bool_true;
767edb885cbSTobias Grosser 
768edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
769edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
770edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
771edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
772edb885cbSTobias Grosser   isl_id_free(Id);
773edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
774edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
775edb885cbSTobias Grosser 
776edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
777edb885cbSTobias Grosser     return isl_bool_true;
778edb885cbSTobias Grosser 
779edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
780edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
781edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
782edb885cbSTobias Grosser   isl_id_free(Id);
783edb885cbSTobias Grosser 
784*00bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
785edb885cbSTobias Grosser 
786edb885cbSTobias Grosser   return isl_bool_true;
787edb885cbSTobias Grosser }
788edb885cbSTobias Grosser 
789edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
790edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
791edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
792edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
793edb885cbSTobias Grosser   SubtreeReferences References = {
794edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
795edb885cbSTobias Grosser 
796edb885cbSTobias Grosser   for (const auto &I : IDToValue)
797edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
798edb885cbSTobias Grosser 
799edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
800edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
801edb885cbSTobias Grosser 
802edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
803edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
804edb885cbSTobias Grosser 
805edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
806d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
807edb885cbSTobias Grosser 
808edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
809edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
810edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
811edb885cbSTobias Grosser     assert(IDToValue.count(Id));
812edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
813edb885cbSTobias Grosser     SubtreeValues.remove(Val);
814edb885cbSTobias Grosser     isl_id_free(Id);
815edb885cbSTobias Grosser   }
816edb885cbSTobias Grosser   isl_space_free(Space);
817edb885cbSTobias Grosser 
818edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
819edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
820edb885cbSTobias Grosser     assert(IDToValue.count(Id));
821edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
822edb885cbSTobias Grosser     SubtreeValues.remove(Val);
823edb885cbSTobias Grosser     isl_id_free(Id);
824edb885cbSTobias Grosser   }
825edb885cbSTobias Grosser 
826edb885cbSTobias Grosser   return SubtreeValues;
827edb885cbSTobias Grosser }
828edb885cbSTobias Grosser 
82974dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
83074dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
83174dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
83274dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
83374dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
83474dc3cb4STobias Grosser 
83574dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
83674dc3cb4STobias Grosser     DT.eraseNode(BB);
83774dc3cb4STobias Grosser }
83874dc3cb4STobias Grosser 
83974dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
84074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
84174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
84274dc3cb4STobias Grosser     if (L)
84374dc3cb4STobias Grosser       SE.forgetLoop(L);
84474dc3cb4STobias Grosser   }
84574dc3cb4STobias Grosser }
84674dc3cb4STobias Grosser 
84774dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
84874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
84974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
85074dc3cb4STobias Grosser     if (L)
85174dc3cb4STobias Grosser       SE.forgetLoop(L);
85274dc3cb4STobias Grosser     LI.removeBlock(&BB);
85374dc3cb4STobias Grosser   }
85474dc3cb4STobias Grosser }
85574dc3cb4STobias Grosser 
85679a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
85779a947c2STobias Grosser   std::vector<Value *> Sizes;
85879a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
85979a947c2STobias Grosser 
86079a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
86179a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
86279a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
86379a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
86479a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
86579a947c2STobias Grosser     Sizes.push_back(Res);
86679a947c2STobias Grosser   }
86779a947c2STobias Grosser   isl_ast_build_free(Context);
86879a947c2STobias Grosser 
86979a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
87079a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
87179a947c2STobias Grosser 
87279a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
87379a947c2STobias Grosser }
87479a947c2STobias Grosser 
87579a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
87679a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
87779a947c2STobias Grosser   std::vector<Value *> Sizes;
87879a947c2STobias Grosser 
87979a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
88079a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
88179a947c2STobias Grosser     Sizes.push_back(Res);
88279a947c2STobias Grosser   }
88379a947c2STobias Grosser 
88479a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
88579a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
88679a947c2STobias Grosser 
88779a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
88879a947c2STobias Grosser }
88979a947c2STobias Grosser 
89057693272STobias Grosser Value *
89157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
89257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
8934e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
8944e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
89579a947c2STobias Grosser 
89679a947c2STobias Grosser   BasicBlock *EntryBlock =
89779a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
89879a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
89979a947c2STobias Grosser   Instruction *Parameters =
90079a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
90179a947c2STobias Grosser 
90279a947c2STobias Grosser   int Index = 0;
90379a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
90479a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
90579a947c2STobias Grosser       continue;
90679a947c2STobias Grosser 
90779a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
90879a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
90979a947c2STobias Grosser 
91079a947c2STobias Grosser     Value *DevArray = DeviceAllocations[(ScopArrayInfo *)SAI];
91179a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
91279a947c2STobias Grosser     Instruction *Param = new AllocaInst(
91379a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
91479a947c2STobias Grosser         EntryBlock->getTerminator());
91579a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
91644143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
91744143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
91879a947c2STobias Grosser     Value *ParamTyped =
91979a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
92079a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
92179a947c2STobias Grosser     Index++;
92279a947c2STobias Grosser   }
92379a947c2STobias Grosser 
924a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
925a490147cSTobias Grosser 
926a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
927a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
928a490147cSTobias Grosser     Value *Val = IDToValue[Id];
929a490147cSTobias Grosser     isl_id_free(Id);
930a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
931a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
932a490147cSTobias Grosser         EntryBlock->getTerminator());
933a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
934a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
935a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
936a490147cSTobias Grosser     Value *ParamTyped =
937a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
938a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
939a490147cSTobias Grosser     Index++;
940a490147cSTobias Grosser   }
941a490147cSTobias Grosser 
942d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
943d8b94bcaSTobias Grosser 
944d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
945d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
946d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
947d8b94bcaSTobias Grosser     isl_id_free(Id);
948d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
949d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
950d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
951d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
952d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
953d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
954d8b94bcaSTobias Grosser     Value *ParamTyped =
955d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
956d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
957d8b94bcaSTobias Grosser     Index++;
958d8b94bcaSTobias Grosser   }
959d8b94bcaSTobias Grosser 
96057693272STobias Grosser   for (auto Val : SubtreeValues) {
96157693272STobias Grosser     Instruction *Param = new AllocaInst(
96257693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
96357693272STobias Grosser         EntryBlock->getTerminator());
96457693272STobias Grosser     Builder.CreateStore(Val, Param);
96557693272STobias Grosser     Value *Slot = Builder.CreateGEP(
96657693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
96757693272STobias Grosser     Value *ParamTyped =
96857693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
96957693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
97057693272STobias Grosser     Index++;
97157693272STobias Grosser   }
97257693272STobias Grosser 
97379a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
97479a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
97579a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
97679a947c2STobias Grosser }
97779a947c2STobias Grosser 
97832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
97932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
98032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
98132837fe3STobias Grosser   isl_id_free(Id);
98232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
98332837fe3STobias Grosser 
984edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
985edb885cbSTobias Grosser 
98632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
98732837fe3STobias Grosser 
98832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
989472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
990edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
99132837fe3STobias Grosser 
992edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
993edb885cbSTobias Grosser 
994edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
995edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
996edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
997edb885cbSTobias Grosser   for (const Loop *L : Loops) {
998edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
999edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1000edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1001edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1002edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1003edb885cbSTobias Grosser     SubtreeValues.insert(V);
1004edb885cbSTobias Grosser   }
1005edb885cbSTobias Grosser 
1006edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
100732837fe3STobias Grosser 
100859ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
100959ab0705STobias Grosser 
101074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
101174dc3cb4STobias Grosser   clearDominators(F);
101274dc3cb4STobias Grosser   clearScalarEvolution(F);
101374dc3cb4STobias Grosser   clearLoops(F);
101474dc3cb4STobias Grosser 
101532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1016472f9654STobias Grosser   IDToValue = HostIDs;
101732837fe3STobias Grosser 
1018edb885cbSTobias Grosser   ValueMap = HostValueMap;
1019edb885cbSTobias Grosser   ScalarMap.clear();
1020edb885cbSTobias Grosser   PHIOpMap.clear();
1021edb885cbSTobias Grosser   EscapeMap.clear();
1022edb885cbSTobias Grosser   IDToSAI.clear();
102374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
102474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
102574dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
102674dc3cb4STobias Grosser   LocalArrays.clear();
1027edb885cbSTobias Grosser 
102857693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
102979a947c2STobias Grosser 
103057793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
103157793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
103257793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
103357793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
103457793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
103579a947c2STobias Grosser 
103679a947c2STobias Grosser   Value *GridDimX, *GridDimY;
103779a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
103879a947c2STobias Grosser 
103979a947c2STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
104079a947c2STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
104179a947c2STobias Grosser 
104279a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
104379a947c2STobias Grosser                          BlockDimZ, Parameters);
104457793596STobias Grosser   createCallFreeKernel(GPUKernel);
104532837fe3STobias Grosser }
104632837fe3STobias Grosser 
104732837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
104832837fe3STobias Grosser ///
104932837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
105032837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
105132837fe3STobias Grosser   std::string Ret = "e";
105232837fe3STobias Grosser 
105332837fe3STobias Grosser   if (!is64Bit)
105432837fe3STobias Grosser     Ret += "-p:32:32";
105532837fe3STobias Grosser 
105632837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
105732837fe3STobias Grosser 
105832837fe3STobias Grosser   return Ret;
105932837fe3STobias Grosser }
106032837fe3STobias Grosser 
1061edb885cbSTobias Grosser Function *
1062edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1063edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
106432837fe3STobias Grosser   std::vector<Type *> Args;
106532837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
106632837fe3STobias Grosser 
106732837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
106832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
106932837fe3STobias Grosser       continue;
107032837fe3STobias Grosser 
107132837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
107232837fe3STobias Grosser   }
107332837fe3STobias Grosser 
1074f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1075f6044bd0STobias Grosser 
1076f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1077f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1078f6044bd0STobias Grosser 
1079c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1080c84a1995STobias Grosser 
1081c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
1082c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
1083c84a1995STobias Grosser 
1084edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1085edb885cbSTobias Grosser     Args.push_back(V->getType());
1086edb885cbSTobias Grosser 
108732837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
108832837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
108932837fe3STobias Grosser                               GPUModule.get());
109032837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
109132837fe3STobias Grosser 
109232837fe3STobias Grosser   auto Arg = FN->arg_begin();
109332837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
109432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
109532837fe3STobias Grosser       continue;
109632837fe3STobias Grosser 
1097edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1098edb885cbSTobias Grosser 
1099edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1100edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1101edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1102edb885cbSTobias Grosser     Value *Val = &*Arg;
1103edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1104edb885cbSTobias Grosser     isl_ast_build *Build =
1105edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1106edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1107edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1108edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1109edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1110edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1111edb885cbSTobias Grosser     }
1112edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1113edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
111474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1115edb885cbSTobias Grosser 
1116edb885cbSTobias Grosser     isl_ast_build_free(Build);
1117edb885cbSTobias Grosser     isl_id_free(Id);
1118edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
111932837fe3STobias Grosser     Arg++;
112032837fe3STobias Grosser   }
112132837fe3STobias Grosser 
1122f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1123f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1124f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1125f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1126f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1127f6044bd0STobias Grosser     Arg++;
1128f6044bd0STobias Grosser   }
1129f6044bd0STobias Grosser 
1130c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1131c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1132c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
1133c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1134c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1135c84a1995STobias Grosser     Arg++;
1136c84a1995STobias Grosser   }
1137c84a1995STobias Grosser 
1138edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1139edb885cbSTobias Grosser     Arg->setName(V->getName());
1140edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1141edb885cbSTobias Grosser     Arg++;
1142edb885cbSTobias Grosser   }
1143edb885cbSTobias Grosser 
114432837fe3STobias Grosser   return FN;
114532837fe3STobias Grosser }
114632837fe3STobias Grosser 
1147472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1148472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1149472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1150472f9654STobias Grosser 
1151472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1152472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1153472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1154472f9654STobias Grosser 
1155472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1156472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1157472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1158472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1159472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1160472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1161472f9654STobias Grosser     IDToValue[Id] = Val;
1162472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1163472f9654STobias Grosser   };
1164472f9654STobias Grosser 
1165472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1166472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1167472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1168472f9654STobias Grosser   }
1169472f9654STobias Grosser 
1170472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1171472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1172472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1173472f9654STobias Grosser   }
1174472f9654STobias Grosser }
1175472f9654STobias Grosser 
1176*00bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1177*00bb5a99STobias Grosser   auto Arg = FN->arg_begin();
1178*00bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
1179*00bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1180*00bb5a99STobias Grosser       continue;
1181*00bb5a99STobias Grosser 
1182*00bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1183*00bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1184*00bb5a99STobias Grosser     isl_id_free(Id);
1185*00bb5a99STobias Grosser 
1186*00bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
1187*00bb5a99STobias Grosser       Arg++;
1188*00bb5a99STobias Grosser       continue;
1189*00bb5a99STobias Grosser     }
1190*00bb5a99STobias Grosser 
1191*00bb5a99STobias Grosser     Value *Alloca = BlockGen.getOrCreateScalarAlloca(SAI->getBasePtr());
1192*00bb5a99STobias Grosser     Value *ArgPtr = &*Arg;
1193*00bb5a99STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
1194*00bb5a99STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1195*00bb5a99STobias Grosser     Value *Val = Builder.CreateLoad(TypedArgPtr);
1196*00bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
1197*00bb5a99STobias Grosser 
1198*00bb5a99STobias Grosser     Arg++;
1199*00bb5a99STobias Grosser   }
1200*00bb5a99STobias Grosser }
1201*00bb5a99STobias Grosser 
1202edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1203edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
120432837fe3STobias Grosser 
120532837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
120632837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
120732837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
120832837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
120932837fe3STobias Grosser 
1210edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
121132837fe3STobias Grosser 
121259ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
121332837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
121432837fe3STobias Grosser 
121559ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
121659ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
121759ab0705STobias Grosser 
121832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
121932837fe3STobias Grosser   Builder.CreateRetVoid();
122032837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1221472f9654STobias Grosser 
1222629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1223629109b6STobias Grosser 
1224*00bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1225472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
122632837fe3STobias Grosser }
122732837fe3STobias Grosser 
122874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
122974dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
123074dc3cb4STobias Grosser   std::string ErrMsg;
123174dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
123274dc3cb4STobias Grosser 
123374dc3cb4STobias Grosser   if (!GPUTarget) {
123474dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
123574dc3cb4STobias Grosser     return "";
123674dc3cb4STobias Grosser   }
123774dc3cb4STobias Grosser 
123874dc3cb4STobias Grosser   TargetOptions Options;
123974dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
124074dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
124174dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
124274dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
124374dc3cb4STobias Grosser 
124474dc3cb4STobias Grosser   SmallString<0> ASMString;
124574dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
124674dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
124774dc3cb4STobias Grosser 
124874dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
124974dc3cb4STobias Grosser 
125074dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
125174dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
125274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
125374dc3cb4STobias Grosser     return "";
125474dc3cb4STobias Grosser   }
125574dc3cb4STobias Grosser 
125674dc3cb4STobias Grosser   PM.run(*GPUModule);
125774dc3cb4STobias Grosser 
125874dc3cb4STobias Grosser   return ASMStream.str();
125974dc3cb4STobias Grosser }
126074dc3cb4STobias Grosser 
126157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
1262e1a98343STobias Grosser   // Verify module.
1263e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
1264e1a98343STobias Grosser   Passes.add(createVerifierPass());
1265e1a98343STobias Grosser   Passes.run(*GPUModule);
126632837fe3STobias Grosser 
126732837fe3STobias Grosser   if (DumpKernelIR)
126832837fe3STobias Grosser     outs() << *GPUModule << "\n";
126932837fe3STobias Grosser 
12709a18d559STobias Grosser   // Optimize module.
12719a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
12729a18d559STobias Grosser   PassManagerBuilder PassBuilder;
12739a18d559STobias Grosser   PassBuilder.OptLevel = 3;
12749a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
12759a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
12769a18d559STobias Grosser   OptPasses.run(*GPUModule);
12779a18d559STobias Grosser 
127874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
127974dc3cb4STobias Grosser 
128074dc3cb4STobias Grosser   if (DumpKernelASM)
128174dc3cb4STobias Grosser     outs() << Assembly << "\n";
128274dc3cb4STobias Grosser 
128332837fe3STobias Grosser   GPUModule.release();
1284472f9654STobias Grosser   KernelIDs.clear();
128557793596STobias Grosser 
128657793596STobias Grosser   return Assembly;
128732837fe3STobias Grosser }
128832837fe3STobias Grosser 
12899dfe4e7cSTobias Grosser namespace {
12909dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
12919dfe4e7cSTobias Grosser public:
12929dfe4e7cSTobias Grosser   static char ID;
12939dfe4e7cSTobias Grosser 
1294e938517eSTobias Grosser   /// The scop that is currently processed.
1295e938517eSTobias Grosser   Scop *S;
1296e938517eSTobias Grosser 
129738fc0aedSTobias Grosser   LoopInfo *LI;
129838fc0aedSTobias Grosser   DominatorTree *DT;
129938fc0aedSTobias Grosser   ScalarEvolution *SE;
130038fc0aedSTobias Grosser   const DataLayout *DL;
130138fc0aedSTobias Grosser   RegionInfo *RI;
130238fc0aedSTobias Grosser 
13039dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
13049dfe4e7cSTobias Grosser 
1305e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1306e938517eSTobias Grosser   ///
1307e938517eSTobias Grosser   /// @returns The compilation options.
1308e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1309e938517eSTobias Grosser     auto DebugOptions =
1310e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1311e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1312e938517eSTobias Grosser 
1313e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1314e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1315e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1316e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
1317e938517eSTobias Grosser 
1318e938517eSTobias Grosser     Options->debug = DebugOptions;
1319e938517eSTobias Grosser 
1320e938517eSTobias Grosser     Options->reschedule = true;
1321e938517eSTobias Grosser     Options->scale_tile_loops = false;
1322e938517eSTobias Grosser     Options->wrap = false;
1323e938517eSTobias Grosser 
1324e938517eSTobias Grosser     Options->non_negative_parameters = false;
1325e938517eSTobias Grosser     Options->ctx = nullptr;
1326e938517eSTobias Grosser     Options->sizes = nullptr;
1327e938517eSTobias Grosser 
13284eaedde5STobias Grosser     Options->tile_size = 32;
13294eaedde5STobias Grosser 
1330e938517eSTobias Grosser     Options->use_private_memory = false;
1331e938517eSTobias Grosser     Options->use_shared_memory = false;
1332e938517eSTobias Grosser     Options->max_shared_memory = 0;
1333e938517eSTobias Grosser 
1334e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1335e938517eSTobias Grosser     Options->openmp = false;
1336e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1337e938517eSTobias Grosser     Options->live_range_reordering = false;
1338e938517eSTobias Grosser 
1339e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1340e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1341e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1342e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1343e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1344e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1345e938517eSTobias Grosser 
1346e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1347e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1348e938517eSTobias Grosser 
1349e938517eSTobias Grosser     return Options;
1350e938517eSTobias Grosser   }
1351e938517eSTobias Grosser 
1352f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1353f384594dSTobias Grosser   ///
1354f384594dSTobias Grosser   /// Instead of a normal access of the form:
1355f384594dSTobias Grosser   ///
1356f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1357f384594dSTobias Grosser   ///
1358f384594dSTobias Grosser   /// a tagged access has the form
1359f384594dSTobias Grosser   ///
1360f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1361f384594dSTobias Grosser   ///
1362f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1363f384594dSTobias Grosser   /// triggered the access.
1364f384594dSTobias Grosser   ///
1365f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1366f384594dSTobias Grosser   ///
1367f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1368f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1369f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1370f384594dSTobias Grosser 
1371f384594dSTobias Grosser     for (auto &Stmt : *S)
1372f384594dSTobias Grosser       for (auto &Acc : Stmt)
1373f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1374f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1375f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1376f384594dSTobias Grosser 
1377f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1378f384594dSTobias Grosser           Space = isl_space_range(Space);
1379f384594dSTobias Grosser           Space = isl_space_from_range(Space);
13806293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1381f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1382f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1383f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1384f384594dSTobias Grosser         }
1385f384594dSTobias Grosser 
1386f384594dSTobias Grosser     return Accesses;
1387f384594dSTobias Grosser   }
1388f384594dSTobias Grosser 
1389f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1390f384594dSTobias Grosser   ///
1391f384594dSTobias Grosser   /// @see getTaggedAccesses
1392f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1393f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1394f384594dSTobias Grosser   }
1395f384594dSTobias Grosser 
1396f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1397f384594dSTobias Grosser   ///
1398f384594dSTobias Grosser   /// @see getTaggedAccesses
1399f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1400f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1401f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1402f384594dSTobias Grosser   }
1403f384594dSTobias Grosser 
1404f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1405f384594dSTobias Grosser   ///
1406f384594dSTobias Grosser   /// @see getTaggedAccesses
1407f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1408f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1409f384594dSTobias Grosser   }
1410f384594dSTobias Grosser 
1411aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1412aef5196fSTobias Grosser   ///
1413aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1414aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1415aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1416aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1417aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1418aef5196fSTobias Grosser   /// the data format that ppcg expects.
1419aef5196fSTobias Grosser   ///
1420aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1421aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1422aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1423bd81a7eeSTobias Grosser         S->getIslCtx(),
1424bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1425aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1426aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1427aef5196fSTobias Grosser 
1428aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1429aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1430aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1431aef5196fSTobias Grosser     }
1432aef5196fSTobias Grosser 
1433aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1434d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1435aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1436aef5196fSTobias Grosser     }
1437aef5196fSTobias Grosser 
1438aef5196fSTobias Grosser     isl_space_free(Space);
1439aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1440aef5196fSTobias Grosser 
1441aef5196fSTobias Grosser     return Names;
1442aef5196fSTobias Grosser   }
1443aef5196fSTobias Grosser 
1444e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1445e938517eSTobias Grosser   ///
1446f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1447f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1448f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1449f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1450e938517eSTobias Grosser   ///
1451e938517eSTobias Grosser   /// @returns A new ppcg scop.
1452e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1453e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1454e938517eSTobias Grosser 
1455e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1456e938517eSTobias Grosser 
1457e938517eSTobias Grosser     PPCGScop->start = 0;
1458e938517eSTobias Grosser     PPCGScop->end = 0;
1459e938517eSTobias Grosser 
1460f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1461f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1462e938517eSTobias Grosser     PPCGScop->call = nullptr;
1463f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1464f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1465e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1466f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1467f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1468f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1469f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1470e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1471f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1472e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1473e938517eSTobias Grosser 
1474e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1475e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1476e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1477e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1478e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1479e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1480e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1481e938517eSTobias Grosser 
1482f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1483aef5196fSTobias Grosser     PPCGScop->names = getNames();
1484e938517eSTobias Grosser 
1485e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1486e938517eSTobias Grosser 
1487f384594dSTobias Grosser     compute_tagger(PPCGScop);
1488f384594dSTobias Grosser     compute_dependences(PPCGScop);
1489f384594dSTobias Grosser 
1490e938517eSTobias Grosser     return PPCGScop;
1491e938517eSTobias Grosser   }
1492e938517eSTobias Grosser 
149360f63b49STobias Grosser   /// Collect the array acesses in a statement.
149460f63b49STobias Grosser   ///
149560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
149660f63b49STobias Grosser   ///
149760f63b49STobias Grosser   /// @returns A list of array accesses.
149860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
149960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
150060f63b49STobias Grosser 
150160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
150260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
150360f63b49STobias Grosser       Access->read = Acc->isRead();
150460f63b49STobias Grosser       Access->write = Acc->isWrite();
150560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
150660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
150760f63b49STobias Grosser       Space = isl_space_range(Space);
150860f63b49STobias Grosser       Space = isl_space_from_range(Space);
15096293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
151060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
151160f63b49STobias Grosser       Access->tagged_access =
151260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
151360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
151460f63b49STobias Grosser       Access->ref_id = Acc->getId();
151560f63b49STobias Grosser       Access->next = Accesses;
151660f63b49STobias Grosser       Accesses = Access;
151760f63b49STobias Grosser     }
151860f63b49STobias Grosser 
151960f63b49STobias Grosser     return Accesses;
152060f63b49STobias Grosser   }
152160f63b49STobias Grosser 
152269b46751STobias Grosser   /// Collect the list of GPU statements.
152369b46751STobias Grosser   ///
152469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
152569b46751STobias Grosser   /// as well as a list with all memory accesses.
152669b46751STobias Grosser   ///
152769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
152869b46751STobias Grosser   ///
152969b46751STobias Grosser   /// @returns A linked-list of statements.
153069b46751STobias Grosser   gpu_stmt *getStatements() {
153169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
153269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
153369b46751STobias Grosser 
153469b46751STobias Grosser     int i = 0;
153569b46751STobias Grosser     for (auto &Stmt : *S) {
153669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
153769b46751STobias Grosser 
153869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
153969b46751STobias Grosser 
154069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
154169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
154260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
154369b46751STobias Grosser       i++;
154469b46751STobias Grosser     }
154569b46751STobias Grosser 
154669b46751STobias Grosser     return Stmts;
154769b46751STobias Grosser   }
154869b46751STobias Grosser 
154960f63b49STobias Grosser   /// Derive the extent of an array.
155060f63b49STobias Grosser   ///
155160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
155260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
155360f63b49STobias Grosser   ///
155460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
155560f63b49STobias Grosser   ///
155660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
155760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
155860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
155960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
156060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
156160f63b49STobias Grosser     isl_set *AccessSet =
156260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
156360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
156460f63b49STobias Grosser 
156560f63b49STobias Grosser     return AccessSet;
156660f63b49STobias Grosser   }
156760f63b49STobias Grosser 
156860f63b49STobias Grosser   /// Derive the bounds of an array.
156960f63b49STobias Grosser   ///
157060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
157160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
157260f63b49STobias Grosser   /// ScopArrayInfo.
157360f63b49STobias Grosser   ///
157460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
157560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
157660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
157760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
157860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
157960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
158060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
158160f63b49STobias Grosser       isl_set_free(Dom);
158260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
158360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
158460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
158560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
158660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
158760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
158860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
158960f63b49STobias Grosser     }
159060f63b49STobias Grosser 
159160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
159260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
159360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
159460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
159560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
159660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
159760f63b49STobias Grosser     }
159860f63b49STobias Grosser   }
159960f63b49STobias Grosser 
160060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
160160f63b49STobias Grosser   ///
160260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
160360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
160460f63b49STobias Grosser     int i = 0;
1605d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
160660f63b49STobias Grosser       std::string TypeName;
160760f63b49STobias Grosser       raw_string_ostream OS(TypeName);
160860f63b49STobias Grosser 
160960f63b49STobias Grosser       OS << *Array->getElementType();
161060f63b49STobias Grosser       TypeName = OS.str();
161160f63b49STobias Grosser 
161260f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
161360f63b49STobias Grosser 
161460f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
161560f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
161660f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
161760f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
161860f63b49STobias Grosser       PPCGArray.extent = nullptr;
161960f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
162060f63b49STobias Grosser       PPCGArray.bound =
162160f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
162260f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
162360f63b49STobias Grosser       PPCGArray.n_ref = 0;
162460f63b49STobias Grosser       PPCGArray.refs = nullptr;
162560f63b49STobias Grosser       PPCGArray.accessed = true;
162660f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
162760f63b49STobias Grosser       PPCGArray.has_compound_element = false;
162860f63b49STobias Grosser       PPCGArray.local = false;
162960f63b49STobias Grosser       PPCGArray.declare_local = false;
163060f63b49STobias Grosser       PPCGArray.global = false;
163160f63b49STobias Grosser       PPCGArray.linearize = false;
163260f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
163313c78e4dSTobias Grosser       PPCGArray.user = Array;
163460f63b49STobias Grosser 
163560f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
16362d010dafSTobias Grosser       i++;
1637b9fc860aSTobias Grosser 
1638b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
163960f63b49STobias Grosser     }
164060f63b49STobias Grosser   }
164160f63b49STobias Grosser 
164260f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
164360f63b49STobias Grosser   ///
164460f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
164560f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
164660f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
164760f63b49STobias Grosser 
1648d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
164960f63b49STobias Grosser       isl_space *Space = Array->getSpace();
165060f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
165160f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
165260f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
165360f63b49STobias Grosser     }
165460f63b49STobias Grosser 
165560f63b49STobias Grosser     return Maps;
165660f63b49STobias Grosser   }
165760f63b49STobias Grosser 
1658e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1659e938517eSTobias Grosser   ///
1660e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1661e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1662e938517eSTobias Grosser 
1663e938517eSTobias Grosser     if (!PPCGScop)
1664e938517eSTobias Grosser       return nullptr;
1665e938517eSTobias Grosser 
1666e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1667e938517eSTobias Grosser 
1668e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1669e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1670aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
167160f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
167260f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
167360f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
167460f63b49STobias Grosser     PPCGProg->tagged_must_kill =
167560f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
167660f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
167760f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
167860f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1679e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1680e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
168169b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
168269b46751STobias Grosser     PPCGProg->stmts = getStatements();
168360f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
168460f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
168560f63b49STobias Grosser                                        PPCGProg->n_array);
168660f63b49STobias Grosser 
168760f63b49STobias Grosser     createArrays(PPCGProg);
1688e938517eSTobias Grosser 
1689e938517eSTobias Grosser     return PPCGProg;
1690e938517eSTobias Grosser   }
1691e938517eSTobias Grosser 
169269b46751STobias Grosser   struct PrintGPUUserData {
169369b46751STobias Grosser     struct cuda_info *CudaInfo;
169469b46751STobias Grosser     struct gpu_prog *PPCGProg;
169569b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
169669b46751STobias Grosser   };
169769b46751STobias Grosser 
169869b46751STobias Grosser   /// Print a user statement node in the host code.
169969b46751STobias Grosser   ///
170069b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
170169b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
170269b46751STobias Grosser   /// host ast.
170369b46751STobias Grosser   ///
170469b46751STobias Grosser   /// @param P The printer to print to
170569b46751STobias Grosser   /// @param Options The printing options to use
170669b46751STobias Grosser   /// @param Node The node to print
170769b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
170869b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
170969b46751STobias Grosser   ///
171069b46751STobias Grosser   /// @returns A printer to which the output has been printed.
171169b46751STobias Grosser   static __isl_give isl_printer *
171269b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
171369b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
171469b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
171569b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
171669b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
171769b46751STobias Grosser 
171869b46751STobias Grosser     if (Id) {
171920251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
172020251734STobias Grosser 
172120251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
172220251734STobias Grosser       // otherwise try to call pet functionality that is not available in
172320251734STobias Grosser       // Polly.
172420251734STobias Grosser       if (IsUser) {
172520251734STobias Grosser         P = isl_printer_start_line(P);
172620251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
172720251734STobias Grosser         P = isl_printer_end_line(P);
172820251734STobias Grosser         isl_id_free(Id);
172920251734STobias Grosser         isl_ast_print_options_free(Options);
173020251734STobias Grosser         return P;
173120251734STobias Grosser       }
173220251734STobias Grosser 
173369b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
173469b46751STobias Grosser       isl_id_free(Id);
173569b46751STobias Grosser       Data->Kernels.push_back(Kernel);
173669b46751STobias Grosser     }
173769b46751STobias Grosser 
173869b46751STobias Grosser     return print_host_user(P, Options, Node, User);
173969b46751STobias Grosser   }
174069b46751STobias Grosser 
174169b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
174269b46751STobias Grosser   ///
174369b46751STobias Grosser   /// @param Kernel The kernel to print
174469b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
174569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
174669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
174769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
174869b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
174969b46751STobias Grosser     char *String = isl_printer_get_str(P);
175069b46751STobias Grosser     printf("%s\n", String);
175169b46751STobias Grosser     free(String);
175269b46751STobias Grosser     isl_printer_free(P);
175369b46751STobias Grosser   }
175469b46751STobias Grosser 
175569b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
175669b46751STobias Grosser   ///
175769b46751STobias Grosser   /// @param Tree An AST describing GPU code
175869b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
175969b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
176069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
176169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
176269b46751STobias Grosser 
176369b46751STobias Grosser     PrintGPUUserData Data;
176469b46751STobias Grosser     Data.PPCGProg = PPCGProg;
176569b46751STobias Grosser 
176669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
176769b46751STobias Grosser     Options =
176869b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
176969b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
177069b46751STobias Grosser     char *String = isl_printer_get_str(P);
177169b46751STobias Grosser     printf("# host\n");
177269b46751STobias Grosser     printf("%s\n", String);
177369b46751STobias Grosser     free(String);
177469b46751STobias Grosser     isl_printer_free(P);
177569b46751STobias Grosser 
177669b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
177769b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
177869b46751STobias Grosser       printKernel(Kernel);
177969b46751STobias Grosser     }
178069b46751STobias Grosser   }
178169b46751STobias Grosser 
1782f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1783f384594dSTobias Grosser   //
1784f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1785f384594dSTobias Grosser   //
1786f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1787f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1788f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1789f384594dSTobias Grosser   //
1790f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1791f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1792f384594dSTobias Grosser   // strategy directly from this pass.
1793f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1794f384594dSTobias Grosser 
1795f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1796f384594dSTobias Grosser 
1797f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1798f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1799f384594dSTobias Grosser     PPCGGen->print = nullptr;
1800f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
180160c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1802f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1803f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1804f384594dSTobias Grosser     PPCGGen->types.n = 0;
1805f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1806f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1807f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1808f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1809f384594dSTobias Grosser 
1810f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1811f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1812f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
18132341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1814f384594dSTobias Grosser 
1815f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1816f384594dSTobias Grosser 
1817aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1818aef5196fSTobias Grosser 
181969b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1820aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
182169b46751STobias Grosser     } else {
1822aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
182369b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
182469b46751STobias Grosser     }
1825aef5196fSTobias Grosser 
1826f384594dSTobias Grosser     if (DumpSchedule) {
1827f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1828f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1829f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1830f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1831f384594dSTobias Grosser       if (Schedule)
1832f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1833f384594dSTobias Grosser       else
1834f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1835f384594dSTobias Grosser 
1836f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1837f384594dSTobias Grosser       isl_printer_free(P);
1838f384594dSTobias Grosser     }
1839f384594dSTobias Grosser 
184069b46751STobias Grosser     if (DumpCode) {
184169b46751STobias Grosser       printf("Code\n");
184269b46751STobias Grosser       printf("====\n");
184369b46751STobias Grosser       if (PPCGGen->tree)
184469b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
184569b46751STobias Grosser       else
184669b46751STobias Grosser         printf("No code generated\n");
184769b46751STobias Grosser     }
184869b46751STobias Grosser 
1849f384594dSTobias Grosser     isl_schedule_free(Schedule);
1850f384594dSTobias Grosser 
1851f384594dSTobias Grosser     return PPCGGen;
1852f384594dSTobias Grosser   }
1853f384594dSTobias Grosser 
1854f384594dSTobias Grosser   /// Free gpu_gen structure.
1855f384594dSTobias Grosser   ///
1856f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1857f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1858f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1859f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1860f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1861f384594dSTobias Grosser     free(PPCGGen);
1862f384594dSTobias Grosser   }
1863f384594dSTobias Grosser 
1864b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1865b307ed4dSTobias Grosser   ///
1866b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1867b307ed4dSTobias Grosser   /// ourselves.
1868b307ed4dSTobias Grosser   ///
1869b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1870b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1871b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1872b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1873b307ed4dSTobias Grosser     free(PPCGScop->options);
1874b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1875b307ed4dSTobias Grosser   }
1876b307ed4dSTobias Grosser 
187738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
187838fc0aedSTobias Grosser   ///
187932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
188032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
188132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
188238fc0aedSTobias Grosser     ScopAnnotator Annotator;
188338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
188438fc0aedSTobias Grosser 
188538fc0aedSTobias Grosser     Region *R = &S->getRegion();
188638fc0aedSTobias Grosser 
188738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
188838fc0aedSTobias Grosser 
188938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
189038fc0aedSTobias Grosser 
189138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
189238fc0aedSTobias Grosser 
189332837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
189432837fe3STobias Grosser                                Prog);
189538fc0aedSTobias Grosser 
189638fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
189738fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
189838fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
189938fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
190038fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
190138fc0aedSTobias Grosser     // code generating this scop.
190238fc0aedSTobias Grosser     BasicBlock *StartBlock =
190338fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
190438fc0aedSTobias Grosser 
190538fc0aedSTobias Grosser     // TODO: Handle LICM
190638fc0aedSTobias Grosser     // TODO: Verify run-time checks
190738fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
190838fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
190938fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
191038fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1911fa7b0802STobias Grosser 
1912fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
191338fc0aedSTobias Grosser     NodeBuilder.create(Root);
19148ed5e599STobias Grosser     NodeBuilder.finalize();
191538fc0aedSTobias Grosser   }
191638fc0aedSTobias Grosser 
1917e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
1918e938517eSTobias Grosser     S = &CurrentScop;
191938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
192038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
192138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
192238fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
192338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1924e938517eSTobias Grosser 
19252d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
19262d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
19272d58a64eSTobias Grosser       return false;
19282d58a64eSTobias Grosser 
1929e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
1930e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
1931f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
193238fc0aedSTobias Grosser 
193338fc0aedSTobias Grosser     if (PPCGGen->tree)
193432837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
193538fc0aedSTobias Grosser 
1936b307ed4dSTobias Grosser     freeOptions(PPCGScop);
1937f384594dSTobias Grosser     freePPCGGen(PPCGGen);
1938e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
1939e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
1940e938517eSTobias Grosser 
1941e938517eSTobias Grosser     return true;
1942e938517eSTobias Grosser   }
19439dfe4e7cSTobias Grosser 
19449dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
19459dfe4e7cSTobias Grosser 
19469dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
19479dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
19489dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
19499dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
19509dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
19519dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
19529dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
19539dfe4e7cSTobias Grosser 
19549dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
19559dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
19569dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
19579dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
19589dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
19599dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
19609dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
19619dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
19629dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
19639dfe4e7cSTobias Grosser 
19649dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
19659dfe4e7cSTobias Grosser     //        region tree.
19669dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
19679dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
19689dfe4e7cSTobias Grosser   }
19699dfe4e7cSTobias Grosser };
19709dfe4e7cSTobias Grosser }
19719dfe4e7cSTobias Grosser 
19729dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
19739dfe4e7cSTobias Grosser 
19749dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
19759dfe4e7cSTobias Grosser 
19769dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
19779dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
19789dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
19799dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
19809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
19819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
19829dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
19839dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
19849dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
19859dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1986