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 
15cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
169dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1738fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
189dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
199dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
20f384594dSTobias Grosser #include "polly/Options.h"
21629109b6STobias Grosser #include "polly/ScopDetection.h"
229dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
23edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2474dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
399dfe4e7cSTobias Grosser 
40f384594dSTobias Grosser #include "isl/union_map.h"
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
48e938517eSTobias Grosser }
49e938517eSTobias Grosser 
509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser using namespace polly;
539dfe4e7cSTobias Grosser using namespace llvm;
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
569dfe4e7cSTobias Grosser 
57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
58f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
59681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
60f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6169b46751STobias Grosser 
6269b46751STobias Grosser static cl::opt<bool>
6369b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6469b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6569b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6669b46751STobias Grosser 
6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6832837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6932837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7032837fe3STobias Grosser                                   cl::cat(PollyCategory));
7132837fe3STobias Grosser 
7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7374dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7474dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7574dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7674dc3cb4STobias Grosser 
7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7874dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7974dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8074dc3cb4STobias Grosser                               cl::cat(PollyCategory));
81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
82b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
83b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
84b513b491STobias Grosser                                   cl::cat(PollyCategory));
85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
86130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
87130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
88130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8974dc3cb4STobias Grosser 
9074dc3cb4STobias Grosser static cl::opt<std::string>
9174dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9274dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9374dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
9474dc3cb4STobias Grosser 
9560c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
9660c60025STobias Grosser ///
9760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
9860c60025STobias Grosser /// of the scheduled ScopStmts.
9960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
100edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10160c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10260c60025STobias Grosser                                        isl_id *Id, void *User),
10360c60025STobias Grosser     void *UserIndex,
10460c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
105edb885cbSTobias Grosser     void *UserExpr) {
10660c60025STobias Grosser 
107edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
10860c60025STobias Grosser 
109edb885cbSTobias Grosser   isl_ctx *Ctx;
110edb885cbSTobias Grosser 
111edb885cbSTobias Grosser   if (!Stmt || !Build)
112edb885cbSTobias Grosser     return NULL;
113edb885cbSTobias Grosser 
114edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
115edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
116edb885cbSTobias Grosser 
117edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
118edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
119edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
120edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
121edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
122edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
123edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
124edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
125edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
126edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
127edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
128edb885cbSTobias Grosser   }
129edb885cbSTobias Grosser 
130edb885cbSTobias Grosser   return RefToExpr;
13160c60025STobias Grosser }
132f384594dSTobias Grosser 
13338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13438fc0aedSTobias Grosser ///
13538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
13638fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
13738fc0aedSTobias Grosser /// for generating GPU specific user nodes.
13838fc0aedSTobias Grosser ///
13938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
14038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14138fc0aedSTobias Grosser public:
14238fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
14338fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
14432837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
145edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
146edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
147edb885cbSTobias Grosser   }
14838fc0aedSTobias Grosser 
149fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
150fa7b0802STobias Grosser   void initializeAfterRTH();
151fa7b0802STobias Grosser 
152fa7b0802STobias Grosser   /// Finalize the generated scop.
153fa7b0802STobias Grosser   virtual void finalize();
154fa7b0802STobias Grosser 
1555857b701STobias Grosser   /// Track if the full build process was successful.
1565857b701STobias Grosser   ///
1575857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1585857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1595857b701STobias Grosser   bool BuildSuccessful = true;
1605857b701STobias Grosser 
16138fc0aedSTobias Grosser private:
16274dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
16374dc3cb4STobias Grosser   ///
16474dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
16574dc3cb4STobias Grosser   /// more.
16674dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
16774dc3cb4STobias Grosser 
16813c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
16913c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1707287aeddSTobias Grosser 
171fa7b0802STobias Grosser   /// The current GPU context.
172fa7b0802STobias Grosser   Value *GPUContext;
173fa7b0802STobias Grosser 
174b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
175b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
176b513b491STobias Grosser 
17732837fe3STobias Grosser   /// A module containing GPU code.
17832837fe3STobias Grosser   ///
17932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
18032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
18132837fe3STobias Grosser 
18232837fe3STobias Grosser   /// The GPU program we generate code for.
18332837fe3STobias Grosser   gpu_prog *Prog;
18432837fe3STobias Grosser 
185472f9654STobias Grosser   /// Class to free isl_ids.
186472f9654STobias Grosser   class IslIdDeleter {
187472f9654STobias Grosser   public:
188472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
189472f9654STobias Grosser   };
190472f9654STobias Grosser 
191472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
192472f9654STobias Grosser   ///
193472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
194472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
195472f9654STobias Grosser 
196edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
197edb885cbSTobias Grosser 
19838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
19938fc0aedSTobias Grosser   ///
20038fc0aedSTobias Grosser   /// These AST nodes can be of type:
20138fc0aedSTobias Grosser   ///
20238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
20338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
20413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2055260c041STobias Grosser   ///   - In-kernel synchronization
2065260c041STobias Grosser   ///   - In-kernel memory copy statement
20738fc0aedSTobias Grosser   ///
2081fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2091fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
21032837fe3STobias Grosser 
21113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
21213c78e4dSTobias Grosser 
21313c78e4dSTobias Grosser   /// Create code for a data transfer statement
21413c78e4dSTobias Grosser   ///
21513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
21613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
21713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
21813c78e4dSTobias Grosser                           enum DataDirection Direction);
21913c78e4dSTobias Grosser 
220edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
221edb885cbSTobias Grosser   ///
222edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
223edb885cbSTobias Grosser   ///
224edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
225edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
226edb885cbSTobias Grosser 
22779a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
22879a947c2STobias Grosser   ///
22979a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
23079a947c2STobias Grosser   ///
23179a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
23279a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
23379a947c2STobias Grosser 
23479a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
23579a947c2STobias Grosser   ///
23679a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
23779a947c2STobias Grosser   ///
23879a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
23979a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
24079a947c2STobias Grosser 
24179a947c2STobias Grosser   /// Create kernel launch parameters.
24279a947c2STobias Grosser   ///
24379a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
24479a947c2STobias Grosser   /// @param F             The kernel function that has been created.
24557693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
24679a947c2STobias Grosser   ///
24779a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
24879a947c2STobias Grosser   ///          values that are passed to the kernel.
24957693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
25057693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
25179a947c2STobias Grosser 
252b513b491STobias Grosser   /// Create declarations for kernel variable.
253b513b491STobias Grosser   ///
254b513b491STobias Grosser   /// This includes shared memory declarations.
255b513b491STobias Grosser   ///
256b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
257b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
258b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
259b513b491STobias Grosser 
260c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
261c1c6a2a6STobias Grosser   ///
262c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
263c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
264c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
265c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
266c1c6a2a6STobias Grosser   /// as specified here.
267c1c6a2a6STobias Grosser   ///
268c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
269c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
270c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
271c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
272c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
273c1c6a2a6STobias Grosser                           Value *BlockDimZ);
274c1c6a2a6STobias Grosser 
27532837fe3STobias Grosser   /// Create GPU kernel.
27632837fe3STobias Grosser   ///
27732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
27832837fe3STobias Grosser   ///
27932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
28032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
28132837fe3STobias Grosser 
28213c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
28313c78e4dSTobias Grosser   ///
28413c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
28513c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
28613c78e4dSTobias Grosser 
28700bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
28800bb5a99STobias Grosser   ///
28900bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
29000bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
29100bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
29200bb5a99STobias Grosser 
29332837fe3STobias Grosser   /// Create kernel function.
29432837fe3STobias Grosser   ///
29532837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
29632837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
29732837fe3STobias Grosser   /// start block of this newly created function.
29832837fe3STobias Grosser   ///
29932837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
300edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
301edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
302edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
30332837fe3STobias Grosser 
30432837fe3STobias Grosser   /// Create the declaration of a kernel function.
30532837fe3STobias Grosser   ///
30632837fe3STobias Grosser   /// The kernel function takes as arguments:
30732837fe3STobias Grosser   ///
30832837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
309f6044bd0STobias Grosser   ///   - Host iterators
310c84a1995STobias Grosser   ///   - Parameters
31132837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
31232837fe3STobias Grosser   ///
31332837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
314edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
315edb885cbSTobias Grosser   ///
31632837fe3STobias Grosser   /// @returns The newly declared function.
317edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
318edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
31932837fe3STobias Grosser 
320472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
321472f9654STobias Grosser   ///
322472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
323472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
324472f9654STobias Grosser 
325b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
326b513b491STobias Grosser   ///
327b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
328b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
329b513b491STobias Grosser 
330edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
331edb885cbSTobias Grosser   ///
332edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
333edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
334edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
335edb885cbSTobias Grosser 
3365260c041STobias Grosser   /// Create an in-kernel synchronization call.
3375260c041STobias Grosser   void createKernelSync();
3385260c041STobias Grosser 
33974dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
34074dc3cb4STobias Grosser   ///
34174dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
34274dc3cb4STobias Grosser   std::string createKernelASM();
34374dc3cb4STobias Grosser 
34474dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
34574dc3cb4STobias Grosser   ///
34674dc3cb4STobias Grosser   /// @param F The function to remove references to.
34774dc3cb4STobias Grosser   void clearDominators(Function *F);
34874dc3cb4STobias Grosser 
34974dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
35074dc3cb4STobias Grosser   ///
35174dc3cb4STobias Grosser   /// @param F The function to remove references to.
35274dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
35374dc3cb4STobias Grosser 
35474dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
35574dc3cb4STobias Grosser   ///
35674dc3cb4STobias Grosser   /// @param F The function to remove references to.
35774dc3cb4STobias Grosser   void clearLoops(Function *F);
35874dc3cb4STobias Grosser 
35932837fe3STobias Grosser   /// Finalize the generation of the kernel function.
36032837fe3STobias Grosser   ///
36132837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
36232837fe3STobias Grosser   /// dump its IR to stderr.
36357793596STobias Grosser   ///
36457793596STobias Grosser   /// @returns The Assembly string of the kernel.
36557793596STobias Grosser   std::string finalizeKernelFunction();
366fa7b0802STobias Grosser 
3677287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
368fa7b0802STobias Grosser   void allocateDeviceArrays();
369fa7b0802STobias Grosser 
3707287aeddSTobias Grosser   /// Free all allocated device arrays.
3717287aeddSTobias Grosser   void freeDeviceArrays();
3727287aeddSTobias Grosser 
373fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
374fa7b0802STobias Grosser   ///
375fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
376fa7b0802STobias Grosser   Value *createCallInitContext();
377fa7b0802STobias Grosser 
37879a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
37979a947c2STobias Grosser   ///
38079a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
38179a947c2STobias Grosser   ///
38279a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
38379a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
38479a947c2STobias Grosser 
385fa7b0802STobias Grosser   /// Create a call to free the GPU context.
386fa7b0802STobias Grosser   ///
387fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
388fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
389fa7b0802STobias Grosser 
3907287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3917287aeddSTobias Grosser   ///
3927287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3937287aeddSTobias Grosser   ///
3947287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
395fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3967287aeddSTobias Grosser 
3977287aeddSTobias Grosser   /// Create a call to free a device array.
3987287aeddSTobias Grosser   ///
3997287aeddSTobias Grosser   /// @param Array The device array to free.
4007287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
40113c78e4dSTobias Grosser 
40213c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
40313c78e4dSTobias Grosser   ///
40413c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
40513c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
40613c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
40713c78e4dSTobias Grosser                                       Value *Size);
40813c78e4dSTobias Grosser 
40913c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
41013c78e4dSTobias Grosser   ///
41113c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
41213c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
41313c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
41413c78e4dSTobias Grosser                                       Value *Size);
41557793596STobias Grosser 
41657793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
41757793596STobias Grosser   ///
41857793596STobias Grosser   /// @param Buffer The string describing the kernel.
41957793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
42057793596STobias Grosser   ///
42157793596STobias Grosser   /// @returns A pointer to a kernel object
42257793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
42357793596STobias Grosser 
42457793596STobias Grosser   /// Create a call to free a GPU kernel.
42557793596STobias Grosser   ///
42657793596STobias Grosser   /// @param GPUKernel THe kernel to free.
42757793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
42879a947c2STobias Grosser 
42979a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
43079a947c2STobias Grosser   ///
43179a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
43279a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
43379a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
43479a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
43579a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
43679a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
43779a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
43879a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
43979a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
44079a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
44179a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
44279a947c2STobias Grosser                               Value *Parameters);
4431fb9b64dSTobias Grosser };
4441fb9b64dSTobias Grosser 
445fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
446750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
447750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
448750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
449750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
450750160e2STobias Grosser 
451fa7b0802STobias Grosser   GPUContext = createCallInitContext();
452fa7b0802STobias Grosser   allocateDeviceArrays();
453fa7b0802STobias Grosser }
454fa7b0802STobias Grosser 
455fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4567287aeddSTobias Grosser   freeDeviceArrays();
457fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
458fa7b0802STobias Grosser   IslNodeBuilder::finalize();
459fa7b0802STobias Grosser }
460fa7b0802STobias Grosser 
461fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
462fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
463fa7b0802STobias Grosser 
464fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
465fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
46613c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4677287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4687287aeddSTobias Grosser     DevArrayName.append(Array->name);
469fa7b0802STobias Grosser 
47013c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
4717287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4727287aeddSTobias Grosser     DevArray->setName(DevArrayName);
47313c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
474fa7b0802STobias Grosser   }
475fa7b0802STobias Grosser 
476fa7b0802STobias Grosser   isl_ast_build_free(Build);
477fa7b0802STobias Grosser }
478fa7b0802STobias Grosser 
479c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
480c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
481c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
482c1c6a2a6STobias Grosser 
483c1c6a2a6STobias Grosser   for (auto &F : *M) {
484c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
485c1c6a2a6STobias Grosser       continue;
486c1c6a2a6STobias Grosser 
487c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
488c1c6a2a6STobias Grosser 
489c1c6a2a6STobias Grosser     Metadata *Elements[] = {
490c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
491c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
492c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
493c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
494c1c6a2a6STobias Grosser     };
495c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
496c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
497c1c6a2a6STobias Grosser   }
498c1c6a2a6STobias Grosser }
499c1c6a2a6STobias Grosser 
5007287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
50113c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
50213c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5037287aeddSTobias Grosser }
5047287aeddSTobias Grosser 
50557793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
50657793596STobias Grosser   const char *Name = "polly_getKernel";
50757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
50857793596STobias Grosser   Function *F = M->getFunction(Name);
50957793596STobias Grosser 
51057793596STobias Grosser   // If F is not available, declare it.
51157793596STobias Grosser   if (!F) {
51257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
51357793596STobias Grosser     std::vector<Type *> Args;
51457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
51557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
51657793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
51757793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
51857793596STobias Grosser   }
51957793596STobias Grosser 
52057793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
52157793596STobias Grosser }
52257793596STobias Grosser 
52379a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
52479a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
52579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
52679a947c2STobias Grosser   Function *F = M->getFunction(Name);
52779a947c2STobias Grosser 
52879a947c2STobias Grosser   // If F is not available, declare it.
52979a947c2STobias Grosser   if (!F) {
53079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
53179a947c2STobias Grosser     std::vector<Type *> Args;
53279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
53379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
53479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
53579a947c2STobias Grosser   }
53679a947c2STobias Grosser 
53779a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
53879a947c2STobias Grosser }
53979a947c2STobias Grosser 
54079a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
54179a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
54279a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
54379a947c2STobias Grosser                                             Value *Parameters) {
54479a947c2STobias Grosser   const char *Name = "polly_launchKernel";
54579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
54679a947c2STobias Grosser   Function *F = M->getFunction(Name);
54779a947c2STobias Grosser 
54879a947c2STobias Grosser   // If F is not available, declare it.
54979a947c2STobias Grosser   if (!F) {
55079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
55179a947c2STobias Grosser     std::vector<Type *> Args;
55279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
55479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
55579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
55679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
55779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
55879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55979a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
56079a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
56179a947c2STobias Grosser   }
56279a947c2STobias Grosser 
56379a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
56479a947c2STobias Grosser                          BlockDimZ, Parameters});
56579a947c2STobias Grosser }
56679a947c2STobias Grosser 
56757793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
56857793596STobias Grosser   const char *Name = "polly_freeKernel";
56957793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
57057793596STobias Grosser   Function *F = M->getFunction(Name);
57157793596STobias Grosser 
57257793596STobias Grosser   // If F is not available, declare it.
57357793596STobias Grosser   if (!F) {
57457793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57557793596STobias Grosser     std::vector<Type *> Args;
57657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
57857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
57957793596STobias Grosser   }
58057793596STobias Grosser 
58157793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
58257793596STobias Grosser }
58357793596STobias Grosser 
5847287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
5857287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
5867287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
5877287aeddSTobias Grosser   Function *F = M->getFunction(Name);
5887287aeddSTobias Grosser 
5897287aeddSTobias Grosser   // If F is not available, declare it.
5907287aeddSTobias Grosser   if (!F) {
5917287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
5927287aeddSTobias Grosser     std::vector<Type *> Args;
5937287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
5947287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
5957287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
5967287aeddSTobias Grosser   }
5977287aeddSTobias Grosser 
5987287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
5997287aeddSTobias Grosser }
6007287aeddSTobias Grosser 
601fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
602fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
603fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
604fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
605fa7b0802STobias Grosser 
606fa7b0802STobias Grosser   // If F is not available, declare it.
607fa7b0802STobias Grosser   if (!F) {
608fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
609fa7b0802STobias Grosser     std::vector<Type *> Args;
610fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
611fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
612fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
613fa7b0802STobias Grosser   }
614fa7b0802STobias Grosser 
615fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
616fa7b0802STobias Grosser }
617fa7b0802STobias Grosser 
61813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
61913c78e4dSTobias Grosser                                                     Value *DeviceData,
62013c78e4dSTobias Grosser                                                     Value *Size) {
62113c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
62213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
62313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
62413c78e4dSTobias Grosser 
62513c78e4dSTobias Grosser   // If F is not available, declare it.
62613c78e4dSTobias Grosser   if (!F) {
62713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
62813c78e4dSTobias Grosser     std::vector<Type *> Args;
62913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
63213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
63313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
63413c78e4dSTobias Grosser   }
63513c78e4dSTobias Grosser 
63613c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
63713c78e4dSTobias Grosser }
63813c78e4dSTobias Grosser 
63913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
64013c78e4dSTobias Grosser                                                     Value *HostData,
64113c78e4dSTobias Grosser                                                     Value *Size) {
64213c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
64313c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
64413c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
64513c78e4dSTobias Grosser 
64613c78e4dSTobias Grosser   // If F is not available, declare it.
64713c78e4dSTobias Grosser   if (!F) {
64813c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
64913c78e4dSTobias Grosser     std::vector<Type *> Args;
65013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65213c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
65313c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
65413c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
65513c78e4dSTobias Grosser   }
65613c78e4dSTobias Grosser 
65713c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
65813c78e4dSTobias Grosser }
65913c78e4dSTobias Grosser 
660fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
661fa7b0802STobias Grosser   const char *Name = "polly_initContext";
662fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
663fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
664fa7b0802STobias Grosser 
665fa7b0802STobias Grosser   // If F is not available, declare it.
666fa7b0802STobias Grosser   if (!F) {
667fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
668fa7b0802STobias Grosser     std::vector<Type *> Args;
669fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
670fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
671fa7b0802STobias Grosser   }
672fa7b0802STobias Grosser 
673fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
674fa7b0802STobias Grosser }
675fa7b0802STobias Grosser 
676fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
677fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
678fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
679fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
680fa7b0802STobias Grosser 
681fa7b0802STobias Grosser   // If F is not available, declare it.
682fa7b0802STobias Grosser   if (!F) {
683fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
684fa7b0802STobias Grosser     std::vector<Type *> Args;
685fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
686fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
687fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
688fa7b0802STobias Grosser   }
689fa7b0802STobias Grosser 
690fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
691fa7b0802STobias Grosser }
692fa7b0802STobias Grosser 
6935260c041STobias Grosser /// Check if one string is a prefix of another.
6945260c041STobias Grosser ///
6955260c041STobias Grosser /// @param String The string in which to look for the prefix.
6965260c041STobias Grosser /// @param Prefix The prefix to look for.
6975260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
6985260c041STobias Grosser   return String.find(Prefix) == 0;
6995260c041STobias Grosser }
7005260c041STobias Grosser 
70113c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
70213c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
70313c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
70413c78e4dSTobias Grosser 
70513c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
70613c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
70713c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
70813c78e4dSTobias Grosser 
70913c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
71013c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
71113c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
71213c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
71313c78e4dSTobias Grosser     }
71413c78e4dSTobias Grosser 
71513c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
716b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
717b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
71813c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
71913c78e4dSTobias Grosser   }
72013c78e4dSTobias Grosser   isl_ast_build_free(Build);
72113c78e4dSTobias Grosser   return ArraySize;
72213c78e4dSTobias Grosser }
72313c78e4dSTobias Grosser 
72413c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
72513c78e4dSTobias Grosser                                         enum DataDirection Direction) {
72613c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
72713c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
72813c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
72913c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
73013c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
73113c78e4dSTobias Grosser 
73213c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
73313c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
73413c78e4dSTobias Grosser 
735b06ff457STobias Grosser   Value *HostPtr;
736b06ff457STobias Grosser 
737b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
738b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
739b06ff457STobias Grosser   else
740b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
74113c78e4dSTobias Grosser 
74213c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
74313c78e4dSTobias Grosser 
74413c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
74513c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
74613c78e4dSTobias Grosser   else
74713c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
74813c78e4dSTobias Grosser 
74913c78e4dSTobias Grosser   isl_id_free(Id);
75013c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
75113c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
75213c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
75313c78e4dSTobias Grosser }
75413c78e4dSTobias Grosser 
7551fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
75632837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
75732837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
75832837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
75932837fe3STobias Grosser   isl_id_free(Id);
76032837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
76132837fe3STobias Grosser 
76232837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
76332837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
76432837fe3STobias Grosser     createKernel(UserStmt);
76532837fe3STobias Grosser     isl_ast_expr_free(Expr);
76632837fe3STobias Grosser     return;
76732837fe3STobias Grosser   }
76832837fe3STobias Grosser 
76913c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
77013c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
77132837fe3STobias Grosser     isl_ast_expr_free(Expr);
77213c78e4dSTobias Grosser     return;
77313c78e4dSTobias Grosser   }
77413c78e4dSTobias Grosser 
77513c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
77613c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
77713c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
77838fc0aedSTobias Grosser     return;
77938fc0aedSTobias Grosser   }
78038fc0aedSTobias Grosser 
7815260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
7825260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
7835260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
7845260c041STobias Grosser   isl_id_free(Anno);
7855260c041STobias Grosser 
7865260c041STobias Grosser   switch (KernelStmt->type) {
7875260c041STobias Grosser   case ppcg_kernel_domain:
788edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
7895260c041STobias Grosser     isl_ast_node_free(UserStmt);
7905260c041STobias Grosser     return;
7915260c041STobias Grosser   case ppcg_kernel_copy:
792b513b491STobias Grosser     createKernelCopy(KernelStmt);
7935260c041STobias Grosser     isl_ast_expr_free(Expr);
7945260c041STobias Grosser     isl_ast_node_free(UserStmt);
7955260c041STobias Grosser     return;
7965260c041STobias Grosser   case ppcg_kernel_sync:
7975260c041STobias Grosser     createKernelSync();
7985260c041STobias Grosser     isl_ast_expr_free(Expr);
7995260c041STobias Grosser     isl_ast_node_free(UserStmt);
8005260c041STobias Grosser     return;
8015260c041STobias Grosser   }
8025260c041STobias Grosser 
8035260c041STobias Grosser   isl_ast_expr_free(Expr);
8045260c041STobias Grosser   isl_ast_node_free(UserStmt);
8055260c041STobias Grosser   return;
8065260c041STobias Grosser }
807b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
808b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
809b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
810b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
811b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
812b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
813b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
814b513b491STobias Grosser 
815b513b491STobias Grosser   if (KernelStmt->u.c.read) {
816b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
817b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
818b513b491STobias Grosser   } else {
819b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
820b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
821b513b491STobias Grosser   }
822b513b491STobias Grosser }
8235260c041STobias Grosser 
824edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
825edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
826edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
827edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
828edb885cbSTobias Grosser 
829edb885cbSTobias Grosser   LoopToScevMapT LTS;
830edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
831edb885cbSTobias Grosser 
832edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
833edb885cbSTobias Grosser 
834edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
835edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
836edb885cbSTobias Grosser   else
837a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
838edb885cbSTobias Grosser }
839edb885cbSTobias Grosser 
8405260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
8415260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8425260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
8435260c041STobias Grosser   Builder.CreateCall(Sync, {});
8445260c041STobias Grosser }
8455260c041STobias Grosser 
846edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
847edb885cbSTobias Grosser ///
848edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
849edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
850edb885cbSTobias Grosser ///
851edb885cbSTobias Grosser /// @param Node The node to collect references for.
852edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
853edb885cbSTobias Grosser ///
854edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
855edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
856edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
857edb885cbSTobias Grosser     return isl_bool_true;
858edb885cbSTobias Grosser 
859edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
860edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
861edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
862edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
863edb885cbSTobias Grosser   isl_id_free(Id);
864edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
865edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
866edb885cbSTobias Grosser 
867edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
868edb885cbSTobias Grosser     return isl_bool_true;
869edb885cbSTobias Grosser 
870edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
871edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
872edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
873edb885cbSTobias Grosser   isl_id_free(Id);
874edb885cbSTobias Grosser 
87500bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
876edb885cbSTobias Grosser 
877edb885cbSTobias Grosser   return isl_bool_true;
878edb885cbSTobias Grosser }
879edb885cbSTobias Grosser 
880edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
881edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
882edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
883edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
884edb885cbSTobias Grosser   SubtreeReferences References = {
885edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
886edb885cbSTobias Grosser 
887edb885cbSTobias Grosser   for (const auto &I : IDToValue)
888edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
889edb885cbSTobias Grosser 
890edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
891edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
892edb885cbSTobias Grosser 
893edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
894edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
895edb885cbSTobias Grosser 
896edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
897d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
898edb885cbSTobias Grosser 
899edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
900edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
901edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
902edb885cbSTobias Grosser     assert(IDToValue.count(Id));
903edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
904edb885cbSTobias Grosser     SubtreeValues.remove(Val);
905edb885cbSTobias Grosser     isl_id_free(Id);
906edb885cbSTobias Grosser   }
907edb885cbSTobias Grosser   isl_space_free(Space);
908edb885cbSTobias Grosser 
909edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
910edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
911edb885cbSTobias Grosser     assert(IDToValue.count(Id));
912edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
913edb885cbSTobias Grosser     SubtreeValues.remove(Val);
914edb885cbSTobias Grosser     isl_id_free(Id);
915edb885cbSTobias Grosser   }
916edb885cbSTobias Grosser 
917edb885cbSTobias Grosser   return SubtreeValues;
918edb885cbSTobias Grosser }
919edb885cbSTobias Grosser 
92074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
92174dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
92274dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
92374dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
92474dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
92574dc3cb4STobias Grosser 
92674dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
92774dc3cb4STobias Grosser     DT.eraseNode(BB);
92874dc3cb4STobias Grosser }
92974dc3cb4STobias Grosser 
93074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
93174dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
93274dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
93374dc3cb4STobias Grosser     if (L)
93474dc3cb4STobias Grosser       SE.forgetLoop(L);
93574dc3cb4STobias Grosser   }
93674dc3cb4STobias Grosser }
93774dc3cb4STobias Grosser 
93874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
93974dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
94074dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
94174dc3cb4STobias Grosser     if (L)
94274dc3cb4STobias Grosser       SE.forgetLoop(L);
94374dc3cb4STobias Grosser     LI.removeBlock(&BB);
94474dc3cb4STobias Grosser   }
94574dc3cb4STobias Grosser }
94674dc3cb4STobias Grosser 
94779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
94879a947c2STobias Grosser   std::vector<Value *> Sizes;
94979a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
95079a947c2STobias Grosser 
95179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
95279a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
95379a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
95479a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
95579a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
95679a947c2STobias Grosser     Sizes.push_back(Res);
95779a947c2STobias Grosser   }
95879a947c2STobias Grosser   isl_ast_build_free(Context);
95979a947c2STobias Grosser 
96079a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
96179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
96279a947c2STobias Grosser 
96379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
96479a947c2STobias Grosser }
96579a947c2STobias Grosser 
96679a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
96779a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
96879a947c2STobias Grosser   std::vector<Value *> Sizes;
96979a947c2STobias Grosser 
97079a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
97179a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
97279a947c2STobias Grosser     Sizes.push_back(Res);
97379a947c2STobias Grosser   }
97479a947c2STobias Grosser 
97579a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
97679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
97779a947c2STobias Grosser 
97879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
97979a947c2STobias Grosser }
98079a947c2STobias Grosser 
98157693272STobias Grosser Value *
98257693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
98357693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
9844e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
9854e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
98679a947c2STobias Grosser 
98779a947c2STobias Grosser   BasicBlock *EntryBlock =
98879a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
98979a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
99079a947c2STobias Grosser   Instruction *Parameters =
99179a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
99279a947c2STobias Grosser 
99379a947c2STobias Grosser   int Index = 0;
99479a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
99579a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
99679a947c2STobias Grosser       continue;
99779a947c2STobias Grosser 
99879a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
99979a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
100079a947c2STobias Grosser 
1001*0a893f7dSTobias Grosser     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
100279a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
100379a947c2STobias Grosser     Instruction *Param = new AllocaInst(
100479a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
100579a947c2STobias Grosser         EntryBlock->getTerminator());
100679a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
100744143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
100844143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
100979a947c2STobias Grosser     Value *ParamTyped =
101079a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
101179a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
101279a947c2STobias Grosser     Index++;
101379a947c2STobias Grosser   }
101479a947c2STobias Grosser 
1015a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1016a490147cSTobias Grosser 
1017a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1018a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1019a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1020a490147cSTobias Grosser     isl_id_free(Id);
1021a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
1022a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1023a490147cSTobias Grosser         EntryBlock->getTerminator());
1024a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1025a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1026a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1027a490147cSTobias Grosser     Value *ParamTyped =
1028a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1029a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1030a490147cSTobias Grosser     Index++;
1031a490147cSTobias Grosser   }
1032a490147cSTobias Grosser 
1033d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1034d8b94bcaSTobias Grosser 
1035d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1036d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1037d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1038d8b94bcaSTobias Grosser     isl_id_free(Id);
1039d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
1040d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1041d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
1042d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1043d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1044d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1045d8b94bcaSTobias Grosser     Value *ParamTyped =
1046d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1047d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1048d8b94bcaSTobias Grosser     Index++;
1049d8b94bcaSTobias Grosser   }
1050d8b94bcaSTobias Grosser 
105157693272STobias Grosser   for (auto Val : SubtreeValues) {
105257693272STobias Grosser     Instruction *Param = new AllocaInst(
105357693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
105457693272STobias Grosser         EntryBlock->getTerminator());
105557693272STobias Grosser     Builder.CreateStore(Val, Param);
105657693272STobias Grosser     Value *Slot = Builder.CreateGEP(
105757693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
105857693272STobias Grosser     Value *ParamTyped =
105957693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
106057693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
106157693272STobias Grosser     Index++;
106257693272STobias Grosser   }
106357693272STobias Grosser 
106479a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
106579a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
106679a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
106779a947c2STobias Grosser }
106879a947c2STobias Grosser 
106932837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
107032837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
107132837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
107232837fe3STobias Grosser   isl_id_free(Id);
107332837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
107432837fe3STobias Grosser 
1075c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1076c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1077c1c6a2a6STobias Grosser 
1078edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1079edb885cbSTobias Grosser 
108032837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
108132837fe3STobias Grosser 
108232837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1083472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1084edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1085b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostScalarMap = ScalarMap;
1086b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostPHIOpMap = PHIOpMap;
1087b06ff457STobias Grosser   ScalarMap.clear();
1088b06ff457STobias Grosser   PHIOpMap.clear();
108932837fe3STobias Grosser 
1090edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1091edb885cbSTobias Grosser 
1092edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1093edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1094edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1095edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1096edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1097edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1098edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1099edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1100edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1101edb885cbSTobias Grosser     SubtreeValues.insert(V);
1102edb885cbSTobias Grosser   }
1103edb885cbSTobias Grosser 
1104edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
110532837fe3STobias Grosser 
110659ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
110759ab0705STobias Grosser 
110874dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1109c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
111074dc3cb4STobias Grosser   clearDominators(F);
111174dc3cb4STobias Grosser   clearScalarEvolution(F);
111274dc3cb4STobias Grosser   clearLoops(F);
111374dc3cb4STobias Grosser 
111432837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1115472f9654STobias Grosser   IDToValue = HostIDs;
111632837fe3STobias Grosser 
1117b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1118b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1119b06ff457STobias Grosser   PHIOpMap = std::move(HostPHIOpMap);
1120edb885cbSTobias Grosser   EscapeMap.clear();
1121edb885cbSTobias Grosser   IDToSAI.clear();
112274dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
112374dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
112474dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
112574dc3cb4STobias Grosser   LocalArrays.clear();
1126edb885cbSTobias Grosser 
112757693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
112879a947c2STobias Grosser 
112957793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
113057793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
113157793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
113257793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
113357793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
113479a947c2STobias Grosser 
113579a947c2STobias Grosser   Value *GridDimX, *GridDimY;
113679a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
113779a947c2STobias Grosser 
113879a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
113979a947c2STobias Grosser                          BlockDimZ, Parameters);
114057793596STobias Grosser   createCallFreeKernel(GPUKernel);
1141b513b491STobias Grosser 
1142b513b491STobias Grosser   for (auto Id : KernelIds)
1143b513b491STobias Grosser     isl_id_free(Id);
1144b513b491STobias Grosser 
1145b513b491STobias Grosser   KernelIds.clear();
114632837fe3STobias Grosser }
114732837fe3STobias Grosser 
114832837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
114932837fe3STobias Grosser ///
115032837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
115132837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
115232837fe3STobias Grosser   std::string Ret = "e";
115332837fe3STobias Grosser 
115432837fe3STobias Grosser   if (!is64Bit)
115532837fe3STobias Grosser     Ret += "-p:32:32";
115632837fe3STobias Grosser 
115732837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
115832837fe3STobias Grosser 
115932837fe3STobias Grosser   return Ret;
116032837fe3STobias Grosser }
116132837fe3STobias Grosser 
1162edb885cbSTobias Grosser Function *
1163edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1164edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
116532837fe3STobias Grosser   std::vector<Type *> Args;
116632837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
116732837fe3STobias Grosser 
116832837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
116932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
117032837fe3STobias Grosser       continue;
117132837fe3STobias Grosser 
117232837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
117332837fe3STobias Grosser   }
117432837fe3STobias Grosser 
1175f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1176f6044bd0STobias Grosser 
1177f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1178f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1179f6044bd0STobias Grosser 
1180c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1181c84a1995STobias Grosser 
1182cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1183cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1184cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1185cf66ef26STobias Grosser     isl_id_free(Id);
1186cf66ef26STobias Grosser     Args.push_back(Val->getType());
1187cf66ef26STobias Grosser   }
1188c84a1995STobias Grosser 
1189edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1190edb885cbSTobias Grosser     Args.push_back(V->getType());
1191edb885cbSTobias Grosser 
119232837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
119332837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
119432837fe3STobias Grosser                               GPUModule.get());
119532837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
119632837fe3STobias Grosser 
119732837fe3STobias Grosser   auto Arg = FN->arg_begin();
119832837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
119932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
120032837fe3STobias Grosser       continue;
120132837fe3STobias Grosser 
1202edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1203edb885cbSTobias Grosser 
1204edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1205edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1206edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1207edb885cbSTobias Grosser     Value *Val = &*Arg;
1208edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1209edb885cbSTobias Grosser     isl_ast_build *Build =
1210edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1211f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1212edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1213edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1214edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1215edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1216edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1217edb885cbSTobias Grosser     }
1218edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1219edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
122074dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1221edb885cbSTobias Grosser 
1222edb885cbSTobias Grosser     isl_ast_build_free(Build);
1223b513b491STobias Grosser     KernelIds.push_back(Id);
1224edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
122532837fe3STobias Grosser     Arg++;
122632837fe3STobias Grosser   }
122732837fe3STobias Grosser 
1228f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1229f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1230f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1231f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1232f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1233f6044bd0STobias Grosser     Arg++;
1234f6044bd0STobias Grosser   }
1235f6044bd0STobias Grosser 
1236c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1237c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1238c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
123912453403STobias Grosser     Value *Val = IDToValue[Id];
124012453403STobias Grosser     ValueMap[Val] = &*Arg;
1241c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1242c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1243c84a1995STobias Grosser     Arg++;
1244c84a1995STobias Grosser   }
1245c84a1995STobias Grosser 
1246edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1247edb885cbSTobias Grosser     Arg->setName(V->getName());
1248edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1249edb885cbSTobias Grosser     Arg++;
1250edb885cbSTobias Grosser   }
1251edb885cbSTobias Grosser 
125232837fe3STobias Grosser   return FN;
125332837fe3STobias Grosser }
125432837fe3STobias Grosser 
1255472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1256472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1257472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1258472f9654STobias Grosser 
1259472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1260472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1261472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1262472f9654STobias Grosser 
1263472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1264472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1265472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1266472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1267472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1268472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1269472f9654STobias Grosser     IDToValue[Id] = Val;
1270472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1271472f9654STobias Grosser   };
1272472f9654STobias Grosser 
1273472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1274472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1275472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1276472f9654STobias Grosser   }
1277472f9654STobias Grosser 
1278472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1279472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1280472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1281472f9654STobias Grosser   }
1282472f9654STobias Grosser }
1283472f9654STobias Grosser 
128400bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
128500bb5a99STobias Grosser   auto Arg = FN->arg_begin();
128600bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
128700bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
128800bb5a99STobias Grosser       continue;
128900bb5a99STobias Grosser 
129000bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
129100bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
129200bb5a99STobias Grosser     isl_id_free(Id);
129300bb5a99STobias Grosser 
129400bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
129500bb5a99STobias Grosser       Arg++;
129600bb5a99STobias Grosser       continue;
129700bb5a99STobias Grosser     }
129800bb5a99STobias Grosser 
1299b06ff457STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
130000bb5a99STobias Grosser     Value *ArgPtr = &*Arg;
130100bb5a99STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
130200bb5a99STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
130300bb5a99STobias Grosser     Value *Val = Builder.CreateLoad(TypedArgPtr);
130400bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
130500bb5a99STobias Grosser 
130600bb5a99STobias Grosser     Arg++;
130700bb5a99STobias Grosser   }
130800bb5a99STobias Grosser }
130900bb5a99STobias Grosser 
1310b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1311b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1312b513b491STobias Grosser 
1313b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1314b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1315b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1316b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1317b513b491STobias Grosser 
1318f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1319b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1320b513b491STobias Grosser 
1321f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1322928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1323b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1324f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1325b513b491STobias Grosser       isl_val_free(Val);
1326b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1327928d7573STobias Grosser     }
1328928d7573STobias Grosser 
1329928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1330928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1331928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1332928d7573STobias Grosser       isl_val_free(Val);
1333b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1334b513b491STobias Grosser     }
1335b513b491STobias Grosser 
1336130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1337130ca30fSTobias Grosser     Value *Allocation;
1338130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1339130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1340130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1341130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1342130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1343f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1344f919d8b3STobias Grosser 
1345130ca30fSTobias Grosser       Allocation = GlobalVar;
1346130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1347130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1348130ca30fSTobias Grosser     } else {
1349130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1350130ca30fSTobias Grosser     }
1351130ca30fSTobias Grosser     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1352130ca30fSTobias Grosser                                      ScopArrayInfo::MK_Array);
1353b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1354130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1355130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1356b513b491STobias Grosser     KernelIds.push_back(Id);
1357b513b491STobias Grosser     IDToSAI[Id] = SAI;
1358b513b491STobias Grosser   }
1359b513b491STobias Grosser }
1360b513b491STobias Grosser 
1361edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1362edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
136332837fe3STobias Grosser 
136432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
136532837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
136632837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
136732837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
136832837fe3STobias Grosser 
1369edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
137032837fe3STobias Grosser 
137159ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
137232837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
137332837fe3STobias Grosser 
137459ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
137559ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
137659ab0705STobias Grosser 
137732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
137832837fe3STobias Grosser   Builder.CreateRetVoid();
137932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1380472f9654STobias Grosser 
1381629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1382629109b6STobias Grosser 
138300bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1384b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1385472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
138632837fe3STobias Grosser }
138732837fe3STobias Grosser 
138874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
138974dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
139074dc3cb4STobias Grosser   std::string ErrMsg;
139174dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
139274dc3cb4STobias Grosser 
139374dc3cb4STobias Grosser   if (!GPUTarget) {
139474dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
139574dc3cb4STobias Grosser     return "";
139674dc3cb4STobias Grosser   }
139774dc3cb4STobias Grosser 
139874dc3cb4STobias Grosser   TargetOptions Options;
139974dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
140074dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
140174dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
140274dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
140374dc3cb4STobias Grosser 
140474dc3cb4STobias Grosser   SmallString<0> ASMString;
140574dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
140674dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
140774dc3cb4STobias Grosser 
140874dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
140974dc3cb4STobias Grosser 
141074dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
141174dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
141274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
141374dc3cb4STobias Grosser     return "";
141474dc3cb4STobias Grosser   }
141574dc3cb4STobias Grosser 
141674dc3cb4STobias Grosser   PM.run(*GPUModule);
141774dc3cb4STobias Grosser 
141874dc3cb4STobias Grosser   return ASMStream.str();
141974dc3cb4STobias Grosser }
142074dc3cb4STobias Grosser 
142157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
14225857b701STobias Grosser   if (verifyModule(*GPUModule)) {
14235857b701STobias Grosser     BuildSuccessful = false;
14245857b701STobias Grosser     return "";
14255857b701STobias Grosser   }
142632837fe3STobias Grosser 
142732837fe3STobias Grosser   if (DumpKernelIR)
142832837fe3STobias Grosser     outs() << *GPUModule << "\n";
142932837fe3STobias Grosser 
14309a18d559STobias Grosser   // Optimize module.
14319a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
14329a18d559STobias Grosser   PassManagerBuilder PassBuilder;
14339a18d559STobias Grosser   PassBuilder.OptLevel = 3;
14349a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
14359a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
14369a18d559STobias Grosser   OptPasses.run(*GPUModule);
14379a18d559STobias Grosser 
143874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
143974dc3cb4STobias Grosser 
144074dc3cb4STobias Grosser   if (DumpKernelASM)
144174dc3cb4STobias Grosser     outs() << Assembly << "\n";
144274dc3cb4STobias Grosser 
144332837fe3STobias Grosser   GPUModule.release();
1444472f9654STobias Grosser   KernelIDs.clear();
144557793596STobias Grosser 
144657793596STobias Grosser   return Assembly;
144732837fe3STobias Grosser }
144832837fe3STobias Grosser 
14499dfe4e7cSTobias Grosser namespace {
14509dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
14519dfe4e7cSTobias Grosser public:
14529dfe4e7cSTobias Grosser   static char ID;
14539dfe4e7cSTobias Grosser 
1454e938517eSTobias Grosser   /// The scop that is currently processed.
1455e938517eSTobias Grosser   Scop *S;
1456e938517eSTobias Grosser 
145738fc0aedSTobias Grosser   LoopInfo *LI;
145838fc0aedSTobias Grosser   DominatorTree *DT;
145938fc0aedSTobias Grosser   ScalarEvolution *SE;
146038fc0aedSTobias Grosser   const DataLayout *DL;
146138fc0aedSTobias Grosser   RegionInfo *RI;
146238fc0aedSTobias Grosser 
14639dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
14649dfe4e7cSTobias Grosser 
1465e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1466e938517eSTobias Grosser   ///
1467e938517eSTobias Grosser   /// @returns The compilation options.
1468e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1469e938517eSTobias Grosser     auto DebugOptions =
1470e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1471e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1472e938517eSTobias Grosser 
1473e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1474e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1475e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1476e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
14778950ceadSTobias Grosser     DebugOptions->verbose = false;
1478e938517eSTobias Grosser 
1479e938517eSTobias Grosser     Options->debug = DebugOptions;
1480e938517eSTobias Grosser 
1481e938517eSTobias Grosser     Options->reschedule = true;
1482e938517eSTobias Grosser     Options->scale_tile_loops = false;
1483e938517eSTobias Grosser     Options->wrap = false;
1484e938517eSTobias Grosser 
1485e938517eSTobias Grosser     Options->non_negative_parameters = false;
1486e938517eSTobias Grosser     Options->ctx = nullptr;
1487e938517eSTobias Grosser     Options->sizes = nullptr;
1488e938517eSTobias Grosser 
14894eaedde5STobias Grosser     Options->tile_size = 32;
14904eaedde5STobias Grosser 
1491130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1492b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1493b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1494e938517eSTobias Grosser 
1495e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1496e938517eSTobias Grosser     Options->openmp = false;
1497e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1498e938517eSTobias Grosser     Options->live_range_reordering = false;
1499e938517eSTobias Grosser 
1500e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1501e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1502e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1503e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1504e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1505e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1506e938517eSTobias Grosser 
1507e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1508e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1509e938517eSTobias Grosser 
1510e938517eSTobias Grosser     return Options;
1511e938517eSTobias Grosser   }
1512e938517eSTobias Grosser 
1513f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1514f384594dSTobias Grosser   ///
1515f384594dSTobias Grosser   /// Instead of a normal access of the form:
1516f384594dSTobias Grosser   ///
1517f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1518f384594dSTobias Grosser   ///
1519f384594dSTobias Grosser   /// a tagged access has the form
1520f384594dSTobias Grosser   ///
1521f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1522f384594dSTobias Grosser   ///
1523f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1524f384594dSTobias Grosser   /// triggered the access.
1525f384594dSTobias Grosser   ///
1526f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1527f384594dSTobias Grosser   ///
1528f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1529f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1530f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1531f384594dSTobias Grosser 
1532f384594dSTobias Grosser     for (auto &Stmt : *S)
1533f384594dSTobias Grosser       for (auto &Acc : Stmt)
1534f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1535f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1536f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1537f384594dSTobias Grosser 
1538f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1539f384594dSTobias Grosser           Space = isl_space_range(Space);
1540f384594dSTobias Grosser           Space = isl_space_from_range(Space);
15416293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1542f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1543f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1544f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1545f384594dSTobias Grosser         }
1546f384594dSTobias Grosser 
1547f384594dSTobias Grosser     return Accesses;
1548f384594dSTobias Grosser   }
1549f384594dSTobias Grosser 
1550f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1551f384594dSTobias Grosser   ///
1552f384594dSTobias Grosser   /// @see getTaggedAccesses
1553f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1554f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1555f384594dSTobias Grosser   }
1556f384594dSTobias Grosser 
1557f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1558f384594dSTobias Grosser   ///
1559f384594dSTobias Grosser   /// @see getTaggedAccesses
1560f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1561f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1562f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1563f384594dSTobias Grosser   }
1564f384594dSTobias Grosser 
1565f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1566f384594dSTobias Grosser   ///
1567f384594dSTobias Grosser   /// @see getTaggedAccesses
1568f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1569f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1570f384594dSTobias Grosser   }
1571f384594dSTobias Grosser 
1572aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1573aef5196fSTobias Grosser   ///
1574aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1575aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1576aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1577aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1578aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1579aef5196fSTobias Grosser   /// the data format that ppcg expects.
1580aef5196fSTobias Grosser   ///
1581aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1582aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1583aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1584bd81a7eeSTobias Grosser         S->getIslCtx(),
1585bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1586aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1587aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1588aef5196fSTobias Grosser 
1589aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1590aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1591aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1592aef5196fSTobias Grosser     }
1593aef5196fSTobias Grosser 
1594aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1595d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1596aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1597aef5196fSTobias Grosser     }
1598aef5196fSTobias Grosser 
1599aef5196fSTobias Grosser     isl_space_free(Space);
1600aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1601aef5196fSTobias Grosser 
1602aef5196fSTobias Grosser     return Names;
1603aef5196fSTobias Grosser   }
1604aef5196fSTobias Grosser 
1605e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1606e938517eSTobias Grosser   ///
1607f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1608f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1609f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1610f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1611e938517eSTobias Grosser   ///
1612e938517eSTobias Grosser   /// @returns A new ppcg scop.
1613e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1614e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1615e938517eSTobias Grosser 
1616e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1617e938517eSTobias Grosser 
1618e938517eSTobias Grosser     PPCGScop->start = 0;
1619e938517eSTobias Grosser     PPCGScop->end = 0;
1620e938517eSTobias Grosser 
1621f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1622f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1623e938517eSTobias Grosser     PPCGScop->call = nullptr;
1624f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1625f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1626e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1627f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1628f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1629f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1630f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1631e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1632f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1633e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1634e938517eSTobias Grosser 
1635e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1636e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1637e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1638e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1639e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1640e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1641e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1642e938517eSTobias Grosser 
1643f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1644aef5196fSTobias Grosser     PPCGScop->names = getNames();
1645e938517eSTobias Grosser 
1646e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1647e938517eSTobias Grosser 
1648f384594dSTobias Grosser     compute_tagger(PPCGScop);
1649f384594dSTobias Grosser     compute_dependences(PPCGScop);
1650f384594dSTobias Grosser 
1651e938517eSTobias Grosser     return PPCGScop;
1652e938517eSTobias Grosser   }
1653e938517eSTobias Grosser 
165460f63b49STobias Grosser   /// Collect the array acesses in a statement.
165560f63b49STobias Grosser   ///
165660f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
165760f63b49STobias Grosser   ///
165860f63b49STobias Grosser   /// @returns A list of array accesses.
165960f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
166060f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
166160f63b49STobias Grosser 
166260f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
166360f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
166460f63b49STobias Grosser       Access->read = Acc->isRead();
166560f63b49STobias Grosser       Access->write = Acc->isWrite();
166660f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
166760f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
166860f63b49STobias Grosser       Space = isl_space_range(Space);
166960f63b49STobias Grosser       Space = isl_space_from_range(Space);
16706293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
167160f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
167260f63b49STobias Grosser       Access->tagged_access =
167360f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1674b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
167560f63b49STobias Grosser       Access->ref_id = Acc->getId();
167660f63b49STobias Grosser       Access->next = Accesses;
1677b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
167860f63b49STobias Grosser       Accesses = Access;
167960f63b49STobias Grosser     }
168060f63b49STobias Grosser 
168160f63b49STobias Grosser     return Accesses;
168260f63b49STobias Grosser   }
168360f63b49STobias Grosser 
168469b46751STobias Grosser   /// Collect the list of GPU statements.
168569b46751STobias Grosser   ///
168669b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
168769b46751STobias Grosser   /// as well as a list with all memory accesses.
168869b46751STobias Grosser   ///
168969b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
169069b46751STobias Grosser   ///
169169b46751STobias Grosser   /// @returns A linked-list of statements.
169269b46751STobias Grosser   gpu_stmt *getStatements() {
169369b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
169469b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
169569b46751STobias Grosser 
169669b46751STobias Grosser     int i = 0;
169769b46751STobias Grosser     for (auto &Stmt : *S) {
169869b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
169969b46751STobias Grosser 
170069b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
170169b46751STobias Grosser 
170269b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
170369b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
170460f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
170569b46751STobias Grosser       i++;
170669b46751STobias Grosser     }
170769b46751STobias Grosser 
170869b46751STobias Grosser     return Stmts;
170969b46751STobias Grosser   }
171069b46751STobias Grosser 
171160f63b49STobias Grosser   /// Derive the extent of an array.
171260f63b49STobias Grosser   ///
1713d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
1714d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
1715d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
1716d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
1717d58acf86STobias Grosser   /// subscript value for the first dimension.
171860f63b49STobias Grosser   ///
171960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
172060f63b49STobias Grosser   ///
172160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
172260f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1723d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
172460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
172560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1726d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
172760f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1728d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1729d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1730d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1731d58acf86STobias Grosser 
1732d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
1733d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1734d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
1735d58acf86STobias Grosser     }
1736d58acf86STobias Grosser 
1737d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
1738d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1739d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
1740d58acf86STobias Grosser     }
1741d58acf86STobias Grosser 
174260f63b49STobias Grosser     isl_set *AccessSet =
174360f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
174460f63b49STobias Grosser 
1745d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
1746d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1747d58acf86STobias Grosser 
1748d58acf86STobias Grosser     isl_pw_aff *Val =
1749d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1750d58acf86STobias Grosser 
1751d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1752d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1753d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1754d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1755d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1756d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1757d58acf86STobias Grosser     OuterMin =
1758d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1759d58acf86STobias Grosser     OuterMax =
1760d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1761d58acf86STobias Grosser 
1762d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
1763d58acf86STobias Grosser 
1764d58acf86STobias Grosser     Extent = isl_set_intersect(
1765d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1766d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1767d58acf86STobias Grosser 
1768d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
1769d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1770d58acf86STobias Grosser 
1771d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
1772d58acf86STobias Grosser       isl_pw_aff *PwAff =
1773d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1774d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1775d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1776d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1777d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
1778d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1779d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1780d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1781d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
1782d58acf86STobias Grosser     }
1783d58acf86STobias Grosser 
1784d58acf86STobias Grosser     return Extent;
178560f63b49STobias Grosser   }
178660f63b49STobias Grosser 
178760f63b49STobias Grosser   /// Derive the bounds of an array.
178860f63b49STobias Grosser   ///
178960f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
179060f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
179160f63b49STobias Grosser   /// ScopArrayInfo.
179260f63b49STobias Grosser   ///
179360f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
179460f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
179560f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
179660f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
179702293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
179802293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
179902293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
180002293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
180102293ed7STobias Grosser         isl_set_free(Dom);
180202293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
180302293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
180402293ed7STobias Grosser       } else {
180560f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
180660f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
180760f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
180860f63b49STobias Grosser         isl_set_free(Dom);
180960f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
181002293ed7STobias Grosser         isl_local_space *LS =
181102293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
181260f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
181360f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
181460f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
181560f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
181660f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
181760f63b49STobias Grosser       }
181802293ed7STobias Grosser     }
181960f63b49STobias Grosser 
182060f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
182160f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
182260f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
182360f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
182460f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
182560f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
182660f63b49STobias Grosser     }
182760f63b49STobias Grosser   }
182860f63b49STobias Grosser 
182960f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
183060f63b49STobias Grosser   ///
183160f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
183260f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
183360f63b49STobias Grosser     int i = 0;
1834d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
183560f63b49STobias Grosser       std::string TypeName;
183660f63b49STobias Grosser       raw_string_ostream OS(TypeName);
183760f63b49STobias Grosser 
183860f63b49STobias Grosser       OS << *Array->getElementType();
183960f63b49STobias Grosser       TypeName = OS.str();
184060f63b49STobias Grosser 
184160f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
184260f63b49STobias Grosser 
184360f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
184460f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
184560f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
184660f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
184760f63b49STobias Grosser       PPCGArray.extent = nullptr;
184860f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
184960f63b49STobias Grosser       PPCGArray.bound =
185060f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
185160f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
185260f63b49STobias Grosser       PPCGArray.n_ref = 0;
185360f63b49STobias Grosser       PPCGArray.refs = nullptr;
185460f63b49STobias Grosser       PPCGArray.accessed = true;
185560f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
185660f63b49STobias Grosser       PPCGArray.has_compound_element = false;
185760f63b49STobias Grosser       PPCGArray.local = false;
185860f63b49STobias Grosser       PPCGArray.declare_local = false;
185960f63b49STobias Grosser       PPCGArray.global = false;
186060f63b49STobias Grosser       PPCGArray.linearize = false;
186160f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
186213c78e4dSTobias Grosser       PPCGArray.user = Array;
186360f63b49STobias Grosser 
186460f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
18652d010dafSTobias Grosser       i++;
1866b9fc860aSTobias Grosser 
1867b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
186860f63b49STobias Grosser     }
186960f63b49STobias Grosser   }
187060f63b49STobias Grosser 
187160f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
187260f63b49STobias Grosser   ///
187360f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
187460f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
187560f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
187660f63b49STobias Grosser 
1877d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
187860f63b49STobias Grosser       isl_space *Space = Array->getSpace();
187960f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
188060f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
188160f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
188260f63b49STobias Grosser     }
188360f63b49STobias Grosser 
188460f63b49STobias Grosser     return Maps;
188560f63b49STobias Grosser   }
188660f63b49STobias Grosser 
1887e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1888e938517eSTobias Grosser   ///
1889e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1890e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1891e938517eSTobias Grosser 
1892e938517eSTobias Grosser     if (!PPCGScop)
1893e938517eSTobias Grosser       return nullptr;
1894e938517eSTobias Grosser 
1895e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1896e938517eSTobias Grosser 
1897e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1898e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1899aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
190060f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
190160f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
190260f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
190360f63b49STobias Grosser     PPCGProg->tagged_must_kill =
190460f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
190560f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
190660f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
1907e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1908e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
190969b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
191069b46751STobias Grosser     PPCGProg->stmts = getStatements();
191160f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
191260f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
191360f63b49STobias Grosser                                        PPCGProg->n_array);
191460f63b49STobias Grosser 
191560f63b49STobias Grosser     createArrays(PPCGProg);
1916e938517eSTobias Grosser 
1917d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1918d58acf86STobias Grosser 
1919e938517eSTobias Grosser     return PPCGProg;
1920e938517eSTobias Grosser   }
1921e938517eSTobias Grosser 
192269b46751STobias Grosser   struct PrintGPUUserData {
192369b46751STobias Grosser     struct cuda_info *CudaInfo;
192469b46751STobias Grosser     struct gpu_prog *PPCGProg;
192569b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
192669b46751STobias Grosser   };
192769b46751STobias Grosser 
192869b46751STobias Grosser   /// Print a user statement node in the host code.
192969b46751STobias Grosser   ///
193069b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
193169b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
193269b46751STobias Grosser   /// host ast.
193369b46751STobias Grosser   ///
193469b46751STobias Grosser   /// @param P The printer to print to
193569b46751STobias Grosser   /// @param Options The printing options to use
193669b46751STobias Grosser   /// @param Node The node to print
193769b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
193869b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
193969b46751STobias Grosser   ///
194069b46751STobias Grosser   /// @returns A printer to which the output has been printed.
194169b46751STobias Grosser   static __isl_give isl_printer *
194269b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
194369b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
194469b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
194569b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
194669b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
194769b46751STobias Grosser 
194869b46751STobias Grosser     if (Id) {
194920251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
195020251734STobias Grosser 
195120251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
195220251734STobias Grosser       // otherwise try to call pet functionality that is not available in
195320251734STobias Grosser       // Polly.
195420251734STobias Grosser       if (IsUser) {
195520251734STobias Grosser         P = isl_printer_start_line(P);
195620251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
195720251734STobias Grosser         P = isl_printer_end_line(P);
195820251734STobias Grosser         isl_id_free(Id);
195920251734STobias Grosser         isl_ast_print_options_free(Options);
196020251734STobias Grosser         return P;
196120251734STobias Grosser       }
196220251734STobias Grosser 
196369b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
196469b46751STobias Grosser       isl_id_free(Id);
196569b46751STobias Grosser       Data->Kernels.push_back(Kernel);
196669b46751STobias Grosser     }
196769b46751STobias Grosser 
196869b46751STobias Grosser     return print_host_user(P, Options, Node, User);
196969b46751STobias Grosser   }
197069b46751STobias Grosser 
197169b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
197269b46751STobias Grosser   ///
197369b46751STobias Grosser   /// @param Kernel The kernel to print
197469b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
197569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
197669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
197769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
197869b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
197969b46751STobias Grosser     char *String = isl_printer_get_str(P);
198069b46751STobias Grosser     printf("%s\n", String);
198169b46751STobias Grosser     free(String);
198269b46751STobias Grosser     isl_printer_free(P);
198369b46751STobias Grosser   }
198469b46751STobias Grosser 
198569b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
198669b46751STobias Grosser   ///
198769b46751STobias Grosser   /// @param Tree An AST describing GPU code
198869b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
198969b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
199069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
199169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
199269b46751STobias Grosser 
199369b46751STobias Grosser     PrintGPUUserData Data;
199469b46751STobias Grosser     Data.PPCGProg = PPCGProg;
199569b46751STobias Grosser 
199669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
199769b46751STobias Grosser     Options =
199869b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
199969b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
200069b46751STobias Grosser     char *String = isl_printer_get_str(P);
200169b46751STobias Grosser     printf("# host\n");
200269b46751STobias Grosser     printf("%s\n", String);
200369b46751STobias Grosser     free(String);
200469b46751STobias Grosser     isl_printer_free(P);
200569b46751STobias Grosser 
200669b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
200769b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
200869b46751STobias Grosser       printKernel(Kernel);
200969b46751STobias Grosser     }
201069b46751STobias Grosser   }
201169b46751STobias Grosser 
2012f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2013f384594dSTobias Grosser   //
2014f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2015f384594dSTobias Grosser   //
2016f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2017f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2018f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2019f384594dSTobias Grosser   //
2020f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2021f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2022f384594dSTobias Grosser   // strategy directly from this pass.
2023f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2024f384594dSTobias Grosser 
2025f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2026f384594dSTobias Grosser 
2027f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2028f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2029f384594dSTobias Grosser     PPCGGen->print = nullptr;
2030f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
203160c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2032f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2033f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2034f384594dSTobias Grosser     PPCGGen->types.n = 0;
2035f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2036f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2037f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2038f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2039f384594dSTobias Grosser 
2040f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2041f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2042f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
20432341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2044f384594dSTobias Grosser 
2045f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2046f384594dSTobias Grosser 
2047aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2048aef5196fSTobias Grosser 
204969b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2050aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
205169b46751STobias Grosser     } else {
2052aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
205369b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
205469b46751STobias Grosser     }
2055aef5196fSTobias Grosser 
2056f384594dSTobias Grosser     if (DumpSchedule) {
2057f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2058f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2059f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2060f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2061f384594dSTobias Grosser       if (Schedule)
2062f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2063f384594dSTobias Grosser       else
2064f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2065f384594dSTobias Grosser 
2066f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2067f384594dSTobias Grosser       isl_printer_free(P);
2068f384594dSTobias Grosser     }
2069f384594dSTobias Grosser 
207069b46751STobias Grosser     if (DumpCode) {
207169b46751STobias Grosser       printf("Code\n");
207269b46751STobias Grosser       printf("====\n");
207369b46751STobias Grosser       if (PPCGGen->tree)
207469b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
207569b46751STobias Grosser       else
207669b46751STobias Grosser         printf("No code generated\n");
207769b46751STobias Grosser     }
207869b46751STobias Grosser 
2079f384594dSTobias Grosser     isl_schedule_free(Schedule);
2080f384594dSTobias Grosser 
2081f384594dSTobias Grosser     return PPCGGen;
2082f384594dSTobias Grosser   }
2083f384594dSTobias Grosser 
2084f384594dSTobias Grosser   /// Free gpu_gen structure.
2085f384594dSTobias Grosser   ///
2086f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2087f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2088f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2089f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2090f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2091f384594dSTobias Grosser     free(PPCGGen);
2092f384594dSTobias Grosser   }
2093f384594dSTobias Grosser 
2094b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2095b307ed4dSTobias Grosser   ///
2096b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2097b307ed4dSTobias Grosser   /// ourselves.
2098b307ed4dSTobias Grosser   ///
2099b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2100b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2101b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2102b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2103b307ed4dSTobias Grosser     free(PPCGScop->options);
2104b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2105b307ed4dSTobias Grosser   }
2106b307ed4dSTobias Grosser 
210738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
210838fc0aedSTobias Grosser   ///
210932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
211032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
211132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
211238fc0aedSTobias Grosser     ScopAnnotator Annotator;
211338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
211438fc0aedSTobias Grosser 
211538fc0aedSTobias Grosser     Region *R = &S->getRegion();
211638fc0aedSTobias Grosser 
211738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
211838fc0aedSTobias Grosser 
211938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
212038fc0aedSTobias Grosser 
212138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
212238fc0aedSTobias Grosser 
212332837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
212432837fe3STobias Grosser                                Prog);
212538fc0aedSTobias Grosser 
212638fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
212738fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
212838fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
212938fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
213038fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
213138fc0aedSTobias Grosser     // code generating this scop.
213238fc0aedSTobias Grosser     BasicBlock *StartBlock =
213338fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
213438fc0aedSTobias Grosser 
213538fc0aedSTobias Grosser     // TODO: Handle LICM
213638fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
213738fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
213838fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2139cb1aef8dSTobias Grosser 
2140cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2141cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2142cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2143cb1aef8dSTobias Grosser 
2144cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2145cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2146cb1aef8dSTobias Grosser 
214738fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2148fa7b0802STobias Grosser 
2149fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
215038fc0aedSTobias Grosser     NodeBuilder.create(Root);
21518ed5e599STobias Grosser     NodeBuilder.finalize();
21525857b701STobias Grosser 
21535857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
21545857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
215538fc0aedSTobias Grosser   }
215638fc0aedSTobias Grosser 
2157e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2158e938517eSTobias Grosser     S = &CurrentScop;
215938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
216038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
216138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
216238fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
216338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2164e938517eSTobias Grosser 
21652d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
21662d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
21672d58a64eSTobias Grosser       return false;
21682d58a64eSTobias Grosser 
2169e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2170e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2171f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
217238fc0aedSTobias Grosser 
217338fc0aedSTobias Grosser     if (PPCGGen->tree)
217432837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
217538fc0aedSTobias Grosser 
2176b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2177f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2178e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2179e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2180e938517eSTobias Grosser 
2181e938517eSTobias Grosser     return true;
2182e938517eSTobias Grosser   }
21839dfe4e7cSTobias Grosser 
21849dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
21859dfe4e7cSTobias Grosser 
21869dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
21879dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
21889dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
21899dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
21909dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
21919dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
21929dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
21939dfe4e7cSTobias Grosser 
21949dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
21959dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
21969dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
21979dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
21989dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
21999dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
22009dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
22019dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
22029dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
22039dfe4e7cSTobias Grosser 
22049dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
22059dfe4e7cSTobias Grosser     //        region tree.
22069dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
22079dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
22089dfe4e7cSTobias Grosser   }
22099dfe4e7cSTobias Grosser };
22109dfe4e7cSTobias Grosser }
22119dfe4e7cSTobias Grosser 
22129dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
22139dfe4e7cSTobias Grosser 
22149dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
22159dfe4e7cSTobias Grosser 
22169dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
22179dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
22189dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
22199dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
22209dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
22219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
22229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
22239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
22249dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
22259dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2226