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 
95*82f2af35STobias Grosser static cl::opt<int>
96*82f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
97*82f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
98*82f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
99*82f2af35STobias Grosser 
10060c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
10160c60025STobias Grosser ///
10260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
10360c60025STobias Grosser /// of the scheduled ScopStmts.
10460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
105edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10660c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10760c60025STobias Grosser                                        isl_id *Id, void *User),
10860c60025STobias Grosser     void *UserIndex,
10960c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
110edb885cbSTobias Grosser     void *UserExpr) {
11160c60025STobias Grosser 
112edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
11360c60025STobias Grosser 
114edb885cbSTobias Grosser   isl_ctx *Ctx;
115edb885cbSTobias Grosser 
116edb885cbSTobias Grosser   if (!Stmt || !Build)
117edb885cbSTobias Grosser     return NULL;
118edb885cbSTobias Grosser 
119edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
120edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
121edb885cbSTobias Grosser 
122edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
123edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
124edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
125edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
126edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
127edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
128edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
129edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
130edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
131edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
132edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
133edb885cbSTobias Grosser   }
134edb885cbSTobias Grosser 
135edb885cbSTobias Grosser   return RefToExpr;
13660c60025STobias Grosser }
137f384594dSTobias Grosser 
13838fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13938fc0aedSTobias Grosser ///
14038fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
14138fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
14238fc0aedSTobias Grosser /// for generating GPU specific user nodes.
14338fc0aedSTobias Grosser ///
14438fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
14538fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14638fc0aedSTobias Grosser public:
14738fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
14838fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
14932837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
150edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
151edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
152edb885cbSTobias Grosser   }
15338fc0aedSTobias Grosser 
154fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
155fa7b0802STobias Grosser   void initializeAfterRTH();
156fa7b0802STobias Grosser 
157fa7b0802STobias Grosser   /// Finalize the generated scop.
158fa7b0802STobias Grosser   virtual void finalize();
159fa7b0802STobias Grosser 
1605857b701STobias Grosser   /// Track if the full build process was successful.
1615857b701STobias Grosser   ///
1625857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1635857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1645857b701STobias Grosser   bool BuildSuccessful = true;
1655857b701STobias Grosser 
16638fc0aedSTobias Grosser private:
16774dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
16874dc3cb4STobias Grosser   ///
16974dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
17074dc3cb4STobias Grosser   /// more.
17174dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
17274dc3cb4STobias Grosser 
17313c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
17413c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1757287aeddSTobias Grosser 
176fa7b0802STobias Grosser   /// The current GPU context.
177fa7b0802STobias Grosser   Value *GPUContext;
178fa7b0802STobias Grosser 
179b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
180b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
181b513b491STobias Grosser 
18232837fe3STobias Grosser   /// A module containing GPU code.
18332837fe3STobias Grosser   ///
18432837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
18532837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
18632837fe3STobias Grosser 
18732837fe3STobias Grosser   /// The GPU program we generate code for.
18832837fe3STobias Grosser   gpu_prog *Prog;
18932837fe3STobias Grosser 
190472f9654STobias Grosser   /// Class to free isl_ids.
191472f9654STobias Grosser   class IslIdDeleter {
192472f9654STobias Grosser   public:
193472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
194472f9654STobias Grosser   };
195472f9654STobias Grosser 
196472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
197472f9654STobias Grosser   ///
198472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
199472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
200472f9654STobias Grosser 
201edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
202edb885cbSTobias Grosser 
20338fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
20438fc0aedSTobias Grosser   ///
20538fc0aedSTobias Grosser   /// These AST nodes can be of type:
20638fc0aedSTobias Grosser   ///
20738fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
20838fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
20913c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2105260c041STobias Grosser   ///   - In-kernel synchronization
2115260c041STobias Grosser   ///   - In-kernel memory copy statement
21238fc0aedSTobias Grosser   ///
2131fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2141fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
21532837fe3STobias Grosser 
21613c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
21713c78e4dSTobias Grosser 
21813c78e4dSTobias Grosser   /// Create code for a data transfer statement
21913c78e4dSTobias Grosser   ///
22013c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
22113c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
22213c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
22313c78e4dSTobias Grosser                           enum DataDirection Direction);
22413c78e4dSTobias Grosser 
225edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
226edb885cbSTobias Grosser   ///
227edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
228edb885cbSTobias Grosser   ///
229edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
230edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
231edb885cbSTobias Grosser 
23279a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
23379a947c2STobias Grosser   ///
23479a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
23579a947c2STobias Grosser   ///
23679a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
23779a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
23879a947c2STobias Grosser 
23979a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
24079a947c2STobias Grosser   ///
24179a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
24279a947c2STobias Grosser   ///
24379a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
24479a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
24579a947c2STobias Grosser 
24679a947c2STobias Grosser   /// Create kernel launch parameters.
24779a947c2STobias Grosser   ///
24879a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
24979a947c2STobias Grosser   /// @param F             The kernel function that has been created.
25057693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
25179a947c2STobias Grosser   ///
25279a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
25379a947c2STobias Grosser   ///          values that are passed to the kernel.
25457693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
25557693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
25679a947c2STobias Grosser 
257b513b491STobias Grosser   /// Create declarations for kernel variable.
258b513b491STobias Grosser   ///
259b513b491STobias Grosser   /// This includes shared memory declarations.
260b513b491STobias Grosser   ///
261b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
262b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
263b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
264b513b491STobias Grosser 
265c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
266c1c6a2a6STobias Grosser   ///
267c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
268c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
269c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
270c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
271c1c6a2a6STobias Grosser   /// as specified here.
272c1c6a2a6STobias Grosser   ///
273c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
274c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
275c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
276c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
277c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
278c1c6a2a6STobias Grosser                           Value *BlockDimZ);
279c1c6a2a6STobias Grosser 
28032837fe3STobias Grosser   /// Create GPU kernel.
28132837fe3STobias Grosser   ///
28232837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
28332837fe3STobias Grosser   ///
28432837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
28532837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
28632837fe3STobias Grosser 
28713c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
28813c78e4dSTobias Grosser   ///
28913c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
29013c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
29113c78e4dSTobias Grosser 
292aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
293aaabbbf8STobias Grosser   ///
294aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
295aaabbbf8STobias Grosser   ///
296aaabbbf8STobias Grosser   /// Example:
297aaabbbf8STobias Grosser   ///
298aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
299aaabbbf8STobias Grosser   ///     A[i + 42] += ...
300aaabbbf8STobias Grosser   ///
301aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
302aaabbbf8STobias Grosser   ///
303aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
304aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
305aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
306aaabbbf8STobias Grosser 
30700bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
30800bb5a99STobias Grosser   ///
30900bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
31000bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
31100bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
31200bb5a99STobias Grosser 
31332837fe3STobias Grosser   /// Create kernel function.
31432837fe3STobias Grosser   ///
31532837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
31632837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
31732837fe3STobias Grosser   /// start block of this newly created function.
31832837fe3STobias Grosser   ///
31932837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
320edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
321edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
322edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
32332837fe3STobias Grosser 
32432837fe3STobias Grosser   /// Create the declaration of a kernel function.
32532837fe3STobias Grosser   ///
32632837fe3STobias Grosser   /// The kernel function takes as arguments:
32732837fe3STobias Grosser   ///
32832837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
329f6044bd0STobias Grosser   ///   - Host iterators
330c84a1995STobias Grosser   ///   - Parameters
33132837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
33232837fe3STobias Grosser   ///
33332837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
334edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
335edb885cbSTobias Grosser   ///
33632837fe3STobias Grosser   /// @returns The newly declared function.
337edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
338edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
33932837fe3STobias Grosser 
340472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
341472f9654STobias Grosser   ///
342472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
343472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
344472f9654STobias Grosser 
345b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
346b513b491STobias Grosser   ///
347b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
348b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
349b513b491STobias Grosser 
350edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
351edb885cbSTobias Grosser   ///
352edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
353edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
354edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
355edb885cbSTobias Grosser 
3565260c041STobias Grosser   /// Create an in-kernel synchronization call.
3575260c041STobias Grosser   void createKernelSync();
3585260c041STobias Grosser 
35974dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
36074dc3cb4STobias Grosser   ///
36174dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
36274dc3cb4STobias Grosser   std::string createKernelASM();
36374dc3cb4STobias Grosser 
36474dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
36574dc3cb4STobias Grosser   ///
36674dc3cb4STobias Grosser   /// @param F The function to remove references to.
36774dc3cb4STobias Grosser   void clearDominators(Function *F);
36874dc3cb4STobias Grosser 
36974dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
37074dc3cb4STobias Grosser   ///
37174dc3cb4STobias Grosser   /// @param F The function to remove references to.
37274dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
37374dc3cb4STobias Grosser 
37474dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
37574dc3cb4STobias Grosser   ///
37674dc3cb4STobias Grosser   /// @param F The function to remove references to.
37774dc3cb4STobias Grosser   void clearLoops(Function *F);
37874dc3cb4STobias Grosser 
37932837fe3STobias Grosser   /// Finalize the generation of the kernel function.
38032837fe3STobias Grosser   ///
38132837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
38232837fe3STobias Grosser   /// dump its IR to stderr.
38357793596STobias Grosser   ///
38457793596STobias Grosser   /// @returns The Assembly string of the kernel.
38557793596STobias Grosser   std::string finalizeKernelFunction();
386fa7b0802STobias Grosser 
38751dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
38851dfc275STobias Grosser   ///
38951dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
39051dfc275STobias Grosser   /// stored back to the global memory location they ared backed up with before
39151dfc275STobias Grosser   /// the kernel terminates.
39251dfc275STobias Grosser   ///
39351dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
39451dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
39551dfc275STobias Grosser 
3967287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
397fa7b0802STobias Grosser   void allocateDeviceArrays();
398fa7b0802STobias Grosser 
3997287aeddSTobias Grosser   /// Free all allocated device arrays.
4007287aeddSTobias Grosser   void freeDeviceArrays();
4017287aeddSTobias Grosser 
402fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
403fa7b0802STobias Grosser   ///
404fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
405fa7b0802STobias Grosser   Value *createCallInitContext();
406fa7b0802STobias Grosser 
40779a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
40879a947c2STobias Grosser   ///
40979a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
41079a947c2STobias Grosser   ///
41179a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
41279a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
41379a947c2STobias Grosser 
414fa7b0802STobias Grosser   /// Create a call to free the GPU context.
415fa7b0802STobias Grosser   ///
416fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
417fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
418fa7b0802STobias Grosser 
4197287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4207287aeddSTobias Grosser   ///
4217287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4227287aeddSTobias Grosser   ///
4237287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
424fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4257287aeddSTobias Grosser 
4267287aeddSTobias Grosser   /// Create a call to free a device array.
4277287aeddSTobias Grosser   ///
4287287aeddSTobias Grosser   /// @param Array The device array to free.
4297287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
43013c78e4dSTobias Grosser 
43113c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
43213c78e4dSTobias Grosser   ///
43313c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
43413c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
43513c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
43613c78e4dSTobias Grosser                                       Value *Size);
43713c78e4dSTobias Grosser 
43813c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
43913c78e4dSTobias Grosser   ///
44013c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
44113c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
44213c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
44313c78e4dSTobias Grosser                                       Value *Size);
44457793596STobias Grosser 
44557793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
44657793596STobias Grosser   ///
44757793596STobias Grosser   /// @param Buffer The string describing the kernel.
44857793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
44957793596STobias Grosser   ///
45057793596STobias Grosser   /// @returns A pointer to a kernel object
45157793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
45257793596STobias Grosser 
45357793596STobias Grosser   /// Create a call to free a GPU kernel.
45457793596STobias Grosser   ///
45557793596STobias Grosser   /// @param GPUKernel THe kernel to free.
45657793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
45779a947c2STobias Grosser 
45879a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
45979a947c2STobias Grosser   ///
46079a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
46179a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
46279a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
46379a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
46479a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
46579a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
46679a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
46779a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
46879a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
46979a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
47079a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
47179a947c2STobias Grosser                               Value *Parameters);
4721fb9b64dSTobias Grosser };
4731fb9b64dSTobias Grosser 
474fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
475750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
476750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
477750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
478750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
479750160e2STobias Grosser 
480fa7b0802STobias Grosser   GPUContext = createCallInitContext();
481fa7b0802STobias Grosser   allocateDeviceArrays();
482fa7b0802STobias Grosser }
483fa7b0802STobias Grosser 
484fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4857287aeddSTobias Grosser   freeDeviceArrays();
486fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
487fa7b0802STobias Grosser   IslNodeBuilder::finalize();
488fa7b0802STobias Grosser }
489fa7b0802STobias Grosser 
490fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
491fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
492fa7b0802STobias Grosser 
493fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
494fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
49513c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4967287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4977287aeddSTobias Grosser     DevArrayName.append(Array->name);
498fa7b0802STobias Grosser 
49913c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
500aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
501aaabbbf8STobias Grosser     if (Offset)
502aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
503aaabbbf8STobias Grosser           ArraySize,
504aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
505aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
5067287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
5077287aeddSTobias Grosser     DevArray->setName(DevArrayName);
50813c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
509fa7b0802STobias Grosser   }
510fa7b0802STobias Grosser 
511fa7b0802STobias Grosser   isl_ast_build_free(Build);
512fa7b0802STobias Grosser }
513fa7b0802STobias Grosser 
514c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
515c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
516c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
517c1c6a2a6STobias Grosser 
518c1c6a2a6STobias Grosser   for (auto &F : *M) {
519c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
520c1c6a2a6STobias Grosser       continue;
521c1c6a2a6STobias Grosser 
522c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
523c1c6a2a6STobias Grosser 
524c1c6a2a6STobias Grosser     Metadata *Elements[] = {
525c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
526c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
527c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
528c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
529c1c6a2a6STobias Grosser     };
530c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
531c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
532c1c6a2a6STobias Grosser   }
533c1c6a2a6STobias Grosser }
534c1c6a2a6STobias Grosser 
5357287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
53613c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
53713c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5387287aeddSTobias Grosser }
5397287aeddSTobias Grosser 
54057793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
54157793596STobias Grosser   const char *Name = "polly_getKernel";
54257793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
54357793596STobias Grosser   Function *F = M->getFunction(Name);
54457793596STobias Grosser 
54557793596STobias Grosser   // If F is not available, declare it.
54657793596STobias Grosser   if (!F) {
54757793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
54857793596STobias Grosser     std::vector<Type *> Args;
54957793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55157793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
55257793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
55357793596STobias Grosser   }
55457793596STobias Grosser 
55557793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
55657793596STobias Grosser }
55757793596STobias Grosser 
55879a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
55979a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
56079a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
56179a947c2STobias Grosser   Function *F = M->getFunction(Name);
56279a947c2STobias Grosser 
56379a947c2STobias Grosser   // If F is not available, declare it.
56479a947c2STobias Grosser   if (!F) {
56579a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
56679a947c2STobias Grosser     std::vector<Type *> Args;
56779a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
56879a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
56979a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
57079a947c2STobias Grosser   }
57179a947c2STobias Grosser 
57279a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
57379a947c2STobias Grosser }
57479a947c2STobias Grosser 
57579a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
57679a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
57779a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
57879a947c2STobias Grosser                                             Value *Parameters) {
57979a947c2STobias Grosser   const char *Name = "polly_launchKernel";
58079a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
58179a947c2STobias Grosser   Function *F = M->getFunction(Name);
58279a947c2STobias Grosser 
58379a947c2STobias Grosser   // If F is not available, declare it.
58479a947c2STobias Grosser   if (!F) {
58579a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
58679a947c2STobias Grosser     std::vector<Type *> Args;
58779a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
58879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
58979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
59379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
59579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
59679a947c2STobias Grosser   }
59779a947c2STobias Grosser 
59879a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
59979a947c2STobias Grosser                          BlockDimZ, Parameters});
60079a947c2STobias Grosser }
60179a947c2STobias Grosser 
60257793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
60357793596STobias Grosser   const char *Name = "polly_freeKernel";
60457793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
60557793596STobias Grosser   Function *F = M->getFunction(Name);
60657793596STobias Grosser 
60757793596STobias Grosser   // If F is not available, declare it.
60857793596STobias Grosser   if (!F) {
60957793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
61057793596STobias Grosser     std::vector<Type *> Args;
61157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
61257793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
61357793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
61457793596STobias Grosser   }
61557793596STobias Grosser 
61657793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
61757793596STobias Grosser }
61857793596STobias Grosser 
6197287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
6207287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
6217287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6227287aeddSTobias Grosser   Function *F = M->getFunction(Name);
6237287aeddSTobias Grosser 
6247287aeddSTobias Grosser   // If F is not available, declare it.
6257287aeddSTobias Grosser   if (!F) {
6267287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
6277287aeddSTobias Grosser     std::vector<Type *> Args;
6287287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
6297287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
6307287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
6317287aeddSTobias Grosser   }
6327287aeddSTobias Grosser 
6337287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
6347287aeddSTobias Grosser }
6357287aeddSTobias Grosser 
636fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
637fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
638fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
639fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
640fa7b0802STobias Grosser 
641fa7b0802STobias Grosser   // If F is not available, declare it.
642fa7b0802STobias Grosser   if (!F) {
643fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
644fa7b0802STobias Grosser     std::vector<Type *> Args;
645fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
646fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
647fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
648fa7b0802STobias Grosser   }
649fa7b0802STobias Grosser 
650fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
651fa7b0802STobias Grosser }
652fa7b0802STobias Grosser 
65313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
65413c78e4dSTobias Grosser                                                     Value *DeviceData,
65513c78e4dSTobias Grosser                                                     Value *Size) {
65613c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
65713c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
65813c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser   // If F is not available, declare it.
66113c78e4dSTobias Grosser   if (!F) {
66213c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
66313c78e4dSTobias Grosser     std::vector<Type *> Args;
66413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
66513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
66613c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
66713c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
66813c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
66913c78e4dSTobias Grosser   }
67013c78e4dSTobias Grosser 
67113c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
67213c78e4dSTobias Grosser }
67313c78e4dSTobias Grosser 
67413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
67513c78e4dSTobias Grosser                                                     Value *HostData,
67613c78e4dSTobias Grosser                                                     Value *Size) {
67713c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
67813c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
67913c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
68013c78e4dSTobias Grosser 
68113c78e4dSTobias Grosser   // If F is not available, declare it.
68213c78e4dSTobias Grosser   if (!F) {
68313c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
68413c78e4dSTobias Grosser     std::vector<Type *> Args;
68513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
68613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
68713c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
68813c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
68913c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
69013c78e4dSTobias Grosser   }
69113c78e4dSTobias Grosser 
69213c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
69313c78e4dSTobias Grosser }
69413c78e4dSTobias Grosser 
695fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
696fa7b0802STobias Grosser   const char *Name = "polly_initContext";
697fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
698fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
699fa7b0802STobias Grosser 
700fa7b0802STobias Grosser   // If F is not available, declare it.
701fa7b0802STobias Grosser   if (!F) {
702fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
703fa7b0802STobias Grosser     std::vector<Type *> Args;
704fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
705fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
706fa7b0802STobias Grosser   }
707fa7b0802STobias Grosser 
708fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
709fa7b0802STobias Grosser }
710fa7b0802STobias Grosser 
711fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
712fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
713fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
714fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
715fa7b0802STobias Grosser 
716fa7b0802STobias Grosser   // If F is not available, declare it.
717fa7b0802STobias Grosser   if (!F) {
718fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
719fa7b0802STobias Grosser     std::vector<Type *> Args;
720fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
721fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
722fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
723fa7b0802STobias Grosser   }
724fa7b0802STobias Grosser 
725fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
726fa7b0802STobias Grosser }
727fa7b0802STobias Grosser 
7285260c041STobias Grosser /// Check if one string is a prefix of another.
7295260c041STobias Grosser ///
7305260c041STobias Grosser /// @param String The string in which to look for the prefix.
7315260c041STobias Grosser /// @param Prefix The prefix to look for.
7325260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
7335260c041STobias Grosser   return String.find(Prefix) == 0;
7345260c041STobias Grosser }
7355260c041STobias Grosser 
73613c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
73713c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
73813c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
73913c78e4dSTobias Grosser 
74013c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
74113c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
74213c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
74313c78e4dSTobias Grosser 
74413c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
74513c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
74613c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
74713c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
74813c78e4dSTobias Grosser     }
74913c78e4dSTobias Grosser 
75013c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
751b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
752b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
75313c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
75413c78e4dSTobias Grosser   }
75513c78e4dSTobias Grosser   isl_ast_build_free(Build);
75613c78e4dSTobias Grosser   return ArraySize;
75713c78e4dSTobias Grosser }
75813c78e4dSTobias Grosser 
759aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
760aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
761aaabbbf8STobias Grosser     return nullptr;
762aaabbbf8STobias Grosser 
763aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
764aaabbbf8STobias Grosser 
765aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
766aaabbbf8STobias Grosser 
767aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
768aaabbbf8STobias Grosser 
769aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
770aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
771aaabbbf8STobias Grosser 
772aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
773aaabbbf8STobias Grosser     isl_set_free(Min);
774aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
775aaabbbf8STobias Grosser     isl_ast_build_free(Build);
776aaabbbf8STobias Grosser     return nullptr;
777aaabbbf8STobias Grosser   }
778aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
779aaabbbf8STobias Grosser 
780aaabbbf8STobias Grosser   isl_ast_expr *Result =
781aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
782aaabbbf8STobias Grosser 
783aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
784aaabbbf8STobias Grosser     if (i > 0) {
785aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
786aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
787aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
788aaabbbf8STobias Grosser     }
789aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
790aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
791aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
792aaabbbf8STobias Grosser   }
793aaabbbf8STobias Grosser 
794aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
795aaabbbf8STobias Grosser   isl_set_free(Min);
796aaabbbf8STobias Grosser   isl_ast_build_free(Build);
797aaabbbf8STobias Grosser 
798aaabbbf8STobias Grosser   return ResultValue;
799aaabbbf8STobias Grosser }
800aaabbbf8STobias Grosser 
80113c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
80213c78e4dSTobias Grosser                                         enum DataDirection Direction) {
80313c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
80413c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
80513c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
80613c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
80713c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
80813c78e4dSTobias Grosser 
80913c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
810aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
81113c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
81213c78e4dSTobias Grosser 
813b06ff457STobias Grosser   Value *HostPtr;
814b06ff457STobias Grosser 
815b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
816b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
817b06ff457STobias Grosser   else
818b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
81913c78e4dSTobias Grosser 
820aaabbbf8STobias Grosser   if (Offset) {
821aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
822aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
823aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
824aaabbbf8STobias Grosser   }
825aaabbbf8STobias Grosser 
82613c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
82713c78e4dSTobias Grosser 
828aaabbbf8STobias Grosser   if (Offset) {
829aaabbbf8STobias Grosser     Size = Builder.CreateSub(
830aaabbbf8STobias Grosser         Size, Builder.CreateMul(
831aaabbbf8STobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
832aaabbbf8STobias Grosser   }
833aaabbbf8STobias Grosser 
83413c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
83513c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
83613c78e4dSTobias Grosser   else
83713c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
83813c78e4dSTobias Grosser 
83913c78e4dSTobias Grosser   isl_id_free(Id);
84013c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
84113c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
84213c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
84313c78e4dSTobias Grosser }
84413c78e4dSTobias Grosser 
8451fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
84632837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
84732837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
84832837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
84932837fe3STobias Grosser   isl_id_free(Id);
85032837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
85132837fe3STobias Grosser 
85232837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
85332837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
85432837fe3STobias Grosser     createKernel(UserStmt);
85532837fe3STobias Grosser     isl_ast_expr_free(Expr);
85632837fe3STobias Grosser     return;
85732837fe3STobias Grosser   }
85832837fe3STobias Grosser 
85913c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
86013c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
86132837fe3STobias Grosser     isl_ast_expr_free(Expr);
86213c78e4dSTobias Grosser     return;
86313c78e4dSTobias Grosser   }
86413c78e4dSTobias Grosser 
86513c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
86613c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
86713c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
86838fc0aedSTobias Grosser     return;
86938fc0aedSTobias Grosser   }
87038fc0aedSTobias Grosser 
8715260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
8725260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
8735260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
8745260c041STobias Grosser   isl_id_free(Anno);
8755260c041STobias Grosser 
8765260c041STobias Grosser   switch (KernelStmt->type) {
8775260c041STobias Grosser   case ppcg_kernel_domain:
878edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
8795260c041STobias Grosser     isl_ast_node_free(UserStmt);
8805260c041STobias Grosser     return;
8815260c041STobias Grosser   case ppcg_kernel_copy:
882b513b491STobias Grosser     createKernelCopy(KernelStmt);
8835260c041STobias Grosser     isl_ast_expr_free(Expr);
8845260c041STobias Grosser     isl_ast_node_free(UserStmt);
8855260c041STobias Grosser     return;
8865260c041STobias Grosser   case ppcg_kernel_sync:
8875260c041STobias Grosser     createKernelSync();
8885260c041STobias Grosser     isl_ast_expr_free(Expr);
8895260c041STobias Grosser     isl_ast_node_free(UserStmt);
8905260c041STobias Grosser     return;
8915260c041STobias Grosser   }
8925260c041STobias Grosser 
8935260c041STobias Grosser   isl_ast_expr_free(Expr);
8945260c041STobias Grosser   isl_ast_node_free(UserStmt);
8955260c041STobias Grosser   return;
8965260c041STobias Grosser }
897b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
898b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
899b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
900b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
901b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
902b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
903b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
904b513b491STobias Grosser 
905b513b491STobias Grosser   if (KernelStmt->u.c.read) {
906b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
907b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
908b513b491STobias Grosser   } else {
909b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
910b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
911b513b491STobias Grosser   }
912b513b491STobias Grosser }
9135260c041STobias Grosser 
914edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
915edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
916edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
917edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
918edb885cbSTobias Grosser 
919edb885cbSTobias Grosser   LoopToScevMapT LTS;
920edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
921edb885cbSTobias Grosser 
922edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
923edb885cbSTobias Grosser 
924edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
925edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
926edb885cbSTobias Grosser   else
927a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
928edb885cbSTobias Grosser }
929edb885cbSTobias Grosser 
9305260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
9315260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9325260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
9335260c041STobias Grosser   Builder.CreateCall(Sync, {});
9345260c041STobias Grosser }
9355260c041STobias Grosser 
936edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
937edb885cbSTobias Grosser ///
938edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
939edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
940edb885cbSTobias Grosser ///
941edb885cbSTobias Grosser /// @param Node The node to collect references for.
942edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
943edb885cbSTobias Grosser ///
944edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
945edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
946edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
947edb885cbSTobias Grosser     return isl_bool_true;
948edb885cbSTobias Grosser 
949edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
950edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
951edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
952edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
953edb885cbSTobias Grosser   isl_id_free(Id);
954edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
955edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
956edb885cbSTobias Grosser 
957edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
958edb885cbSTobias Grosser     return isl_bool_true;
959edb885cbSTobias Grosser 
960edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
961edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
962edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
963edb885cbSTobias Grosser   isl_id_free(Id);
964edb885cbSTobias Grosser 
96500bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
966edb885cbSTobias Grosser 
967edb885cbSTobias Grosser   return isl_bool_true;
968edb885cbSTobias Grosser }
969edb885cbSTobias Grosser 
970edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
971edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
972edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
973edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
974edb885cbSTobias Grosser   SubtreeReferences References = {
975edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
976edb885cbSTobias Grosser 
977edb885cbSTobias Grosser   for (const auto &I : IDToValue)
978edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
979edb885cbSTobias Grosser 
980edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
981edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
982edb885cbSTobias Grosser 
983edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
984edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
985edb885cbSTobias Grosser 
986edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
987d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
988edb885cbSTobias Grosser 
989edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
990edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
991edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
992edb885cbSTobias Grosser     assert(IDToValue.count(Id));
993edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
994edb885cbSTobias Grosser     SubtreeValues.remove(Val);
995edb885cbSTobias Grosser     isl_id_free(Id);
996edb885cbSTobias Grosser   }
997edb885cbSTobias Grosser   isl_space_free(Space);
998edb885cbSTobias Grosser 
999edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1000edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1001edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1002edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1003edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1004edb885cbSTobias Grosser     isl_id_free(Id);
1005edb885cbSTobias Grosser   }
1006edb885cbSTobias Grosser 
1007edb885cbSTobias Grosser   return SubtreeValues;
1008edb885cbSTobias Grosser }
1009edb885cbSTobias Grosser 
101074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
101174dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
101274dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
101374dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
101474dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
101574dc3cb4STobias Grosser 
101674dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
101774dc3cb4STobias Grosser     DT.eraseNode(BB);
101874dc3cb4STobias Grosser }
101974dc3cb4STobias Grosser 
102074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
102174dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
102274dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
102374dc3cb4STobias Grosser     if (L)
102474dc3cb4STobias Grosser       SE.forgetLoop(L);
102574dc3cb4STobias Grosser   }
102674dc3cb4STobias Grosser }
102774dc3cb4STobias Grosser 
102874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
102974dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
103074dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
103174dc3cb4STobias Grosser     if (L)
103274dc3cb4STobias Grosser       SE.forgetLoop(L);
103374dc3cb4STobias Grosser     LI.removeBlock(&BB);
103474dc3cb4STobias Grosser   }
103574dc3cb4STobias Grosser }
103674dc3cb4STobias Grosser 
103779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
103879a947c2STobias Grosser   std::vector<Value *> Sizes;
103979a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
104079a947c2STobias Grosser 
104179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
104279a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
104379a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
104479a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
104579a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
104679a947c2STobias Grosser     Sizes.push_back(Res);
104779a947c2STobias Grosser   }
104879a947c2STobias Grosser   isl_ast_build_free(Context);
104979a947c2STobias Grosser 
105079a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
105179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
105279a947c2STobias Grosser 
105379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
105479a947c2STobias Grosser }
105579a947c2STobias Grosser 
105679a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
105779a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
105879a947c2STobias Grosser   std::vector<Value *> Sizes;
105979a947c2STobias Grosser 
106079a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
106179a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
106279a947c2STobias Grosser     Sizes.push_back(Res);
106379a947c2STobias Grosser   }
106479a947c2STobias Grosser 
106579a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
106679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
106779a947c2STobias Grosser 
106879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
106979a947c2STobias Grosser }
107079a947c2STobias Grosser 
107157693272STobias Grosser Value *
107257693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
107357693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
10744e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
10754e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
107679a947c2STobias Grosser 
107779a947c2STobias Grosser   BasicBlock *EntryBlock =
107879a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
107979a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
108079a947c2STobias Grosser   Instruction *Parameters =
108179a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
108279a947c2STobias Grosser 
108379a947c2STobias Grosser   int Index = 0;
108479a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
108579a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
108679a947c2STobias Grosser       continue;
108779a947c2STobias Grosser 
108879a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
108979a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
109079a947c2STobias Grosser 
10910a893f7dSTobias Grosser     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
109279a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
1093aaabbbf8STobias Grosser 
1094aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1095aaabbbf8STobias Grosser 
1096aaabbbf8STobias Grosser     if (Offset) {
1097aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1098aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1099aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1100aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1101aaabbbf8STobias Grosser     }
1102fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1103fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1104aaabbbf8STobias Grosser 
1105fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1106fe74a7a1STobias Grosser       Value *ValPtr = BlockGen.getOrCreateAlloca(SAI);
1107fe74a7a1STobias Grosser       Value *ValPtrCast =
1108fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1109fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1110fe74a7a1STobias Grosser     } else {
111179a947c2STobias Grosser       Instruction *Param = new AllocaInst(
111279a947c2STobias Grosser           Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
111379a947c2STobias Grosser           EntryBlock->getTerminator());
111479a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
111579a947c2STobias Grosser       Value *ParamTyped =
111679a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
111779a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1118fe74a7a1STobias Grosser     }
111979a947c2STobias Grosser     Index++;
112079a947c2STobias Grosser   }
112179a947c2STobias Grosser 
1122a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1123a490147cSTobias Grosser 
1124a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1125a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1126a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1127a490147cSTobias Grosser     isl_id_free(Id);
1128a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
1129a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1130a490147cSTobias Grosser         EntryBlock->getTerminator());
1131a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1132a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1133a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1134a490147cSTobias Grosser     Value *ParamTyped =
1135a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1136a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1137a490147cSTobias Grosser     Index++;
1138a490147cSTobias Grosser   }
1139a490147cSTobias Grosser 
1140d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1141d8b94bcaSTobias Grosser 
1142d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1143d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1144d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1145d8b94bcaSTobias Grosser     isl_id_free(Id);
1146d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
1147d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1148d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
1149d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1150d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1151d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1152d8b94bcaSTobias Grosser     Value *ParamTyped =
1153d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1154d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1155d8b94bcaSTobias Grosser     Index++;
1156d8b94bcaSTobias Grosser   }
1157d8b94bcaSTobias Grosser 
115857693272STobias Grosser   for (auto Val : SubtreeValues) {
115957693272STobias Grosser     Instruction *Param = new AllocaInst(
116057693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
116157693272STobias Grosser         EntryBlock->getTerminator());
116257693272STobias Grosser     Builder.CreateStore(Val, Param);
116357693272STobias Grosser     Value *Slot = Builder.CreateGEP(
116457693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
116557693272STobias Grosser     Value *ParamTyped =
116657693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
116757693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
116857693272STobias Grosser     Index++;
116957693272STobias Grosser   }
117057693272STobias Grosser 
117179a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
117279a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
117379a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
117479a947c2STobias Grosser }
117579a947c2STobias Grosser 
117632837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
117732837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
117832837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
117932837fe3STobias Grosser   isl_id_free(Id);
118032837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
118132837fe3STobias Grosser 
1182c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1183c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1184c1c6a2a6STobias Grosser 
1185edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1186edb885cbSTobias Grosser 
118732837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
118832837fe3STobias Grosser 
118932837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1190472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1191edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1192b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostScalarMap = ScalarMap;
1193b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostPHIOpMap = PHIOpMap;
1194b06ff457STobias Grosser   ScalarMap.clear();
1195b06ff457STobias Grosser   PHIOpMap.clear();
119632837fe3STobias Grosser 
1197edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1198edb885cbSTobias Grosser 
1199edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1200edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1201edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1202edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1203edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1204edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1205edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1206edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1207edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1208edb885cbSTobias Grosser     SubtreeValues.insert(V);
1209edb885cbSTobias Grosser   }
1210edb885cbSTobias Grosser 
1211edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
121232837fe3STobias Grosser 
121359ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
121459ab0705STobias Grosser 
121551dfc275STobias Grosser   finalizeKernelArguments(Kernel);
121674dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1217c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
121874dc3cb4STobias Grosser   clearDominators(F);
121974dc3cb4STobias Grosser   clearScalarEvolution(F);
122074dc3cb4STobias Grosser   clearLoops(F);
122174dc3cb4STobias Grosser 
1222472f9654STobias Grosser   IDToValue = HostIDs;
122332837fe3STobias Grosser 
1224b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1225b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1226b06ff457STobias Grosser   PHIOpMap = std::move(HostPHIOpMap);
1227edb885cbSTobias Grosser   EscapeMap.clear();
1228edb885cbSTobias Grosser   IDToSAI.clear();
122974dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
123074dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
123174dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
123274dc3cb4STobias Grosser   LocalArrays.clear();
1233edb885cbSTobias Grosser 
123451dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
123551dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
123657693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
123779a947c2STobias Grosser 
123857793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
123957793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
124057793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
124157793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
124279a947c2STobias Grosser 
124379a947c2STobias Grosser   Value *GridDimX, *GridDimY;
124479a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
124579a947c2STobias Grosser 
124679a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
124779a947c2STobias Grosser                          BlockDimZ, Parameters);
124857793596STobias Grosser   createCallFreeKernel(GPUKernel);
1249b513b491STobias Grosser 
1250b513b491STobias Grosser   for (auto Id : KernelIds)
1251b513b491STobias Grosser     isl_id_free(Id);
1252b513b491STobias Grosser 
1253b513b491STobias Grosser   KernelIds.clear();
125432837fe3STobias Grosser }
125532837fe3STobias Grosser 
125632837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
125732837fe3STobias Grosser ///
125832837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
125932837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
126032837fe3STobias Grosser   std::string Ret = "e";
126132837fe3STobias Grosser 
126232837fe3STobias Grosser   if (!is64Bit)
126332837fe3STobias Grosser     Ret += "-p:32:32";
126432837fe3STobias Grosser 
126532837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
126632837fe3STobias Grosser 
126732837fe3STobias Grosser   return Ret;
126832837fe3STobias Grosser }
126932837fe3STobias Grosser 
1270edb885cbSTobias Grosser Function *
1271edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1272edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
127332837fe3STobias Grosser   std::vector<Type *> Args;
127432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
127532837fe3STobias Grosser 
127632837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
127732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
127832837fe3STobias Grosser       continue;
127932837fe3STobias Grosser 
1280fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1281fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1282fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1283fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1284fe74a7a1STobias Grosser     } else {
128532837fe3STobias Grosser       Args.push_back(Builder.getInt8PtrTy());
128632837fe3STobias Grosser     }
1287fe74a7a1STobias Grosser   }
128832837fe3STobias Grosser 
1289f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1290f6044bd0STobias Grosser 
1291f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1292f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1293f6044bd0STobias Grosser 
1294c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1295c84a1995STobias Grosser 
1296cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1297cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1298cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1299cf66ef26STobias Grosser     isl_id_free(Id);
1300cf66ef26STobias Grosser     Args.push_back(Val->getType());
1301cf66ef26STobias Grosser   }
1302c84a1995STobias Grosser 
1303edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1304edb885cbSTobias Grosser     Args.push_back(V->getType());
1305edb885cbSTobias Grosser 
130632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
130732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
130832837fe3STobias Grosser                               GPUModule.get());
130932837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
131032837fe3STobias Grosser 
131132837fe3STobias Grosser   auto Arg = FN->arg_begin();
131232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
131332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
131432837fe3STobias Grosser       continue;
131532837fe3STobias Grosser 
1316edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1317edb885cbSTobias Grosser 
1318edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1319edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1320edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1321edb885cbSTobias Grosser     Value *Val = &*Arg;
1322edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1323edb885cbSTobias Grosser     isl_ast_build *Build =
1324edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1325f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1326edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1327edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1328edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1329edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1330edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1331edb885cbSTobias Grosser     }
1332edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1333edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
133474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1335edb885cbSTobias Grosser 
1336edb885cbSTobias Grosser     isl_ast_build_free(Build);
1337b513b491STobias Grosser     KernelIds.push_back(Id);
1338edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
133932837fe3STobias Grosser     Arg++;
134032837fe3STobias Grosser   }
134132837fe3STobias Grosser 
1342f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1343f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1344f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1345f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1346f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1347f6044bd0STobias Grosser     Arg++;
1348f6044bd0STobias Grosser   }
1349f6044bd0STobias Grosser 
1350c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1351c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1352c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
135312453403STobias Grosser     Value *Val = IDToValue[Id];
135412453403STobias Grosser     ValueMap[Val] = &*Arg;
1355c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1356c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1357c84a1995STobias Grosser     Arg++;
1358c84a1995STobias Grosser   }
1359c84a1995STobias Grosser 
1360edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1361edb885cbSTobias Grosser     Arg->setName(V->getName());
1362edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1363edb885cbSTobias Grosser     Arg++;
1364edb885cbSTobias Grosser   }
1365edb885cbSTobias Grosser 
136632837fe3STobias Grosser   return FN;
136732837fe3STobias Grosser }
136832837fe3STobias Grosser 
1369472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1370472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1371472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1372472f9654STobias Grosser 
1373472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1374472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1375472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1376472f9654STobias Grosser 
1377472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1378472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1379472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1380472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1381472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1382472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1383472f9654STobias Grosser     IDToValue[Id] = Val;
1384472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1385472f9654STobias Grosser   };
1386472f9654STobias Grosser 
1387472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1388472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1389472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1390472f9654STobias Grosser   }
1391472f9654STobias Grosser 
1392472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1393472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1394472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1395472f9654STobias Grosser   }
1396472f9654STobias Grosser }
1397472f9654STobias Grosser 
139800bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
139900bb5a99STobias Grosser   auto Arg = FN->arg_begin();
140000bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
140100bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
140200bb5a99STobias Grosser       continue;
140300bb5a99STobias Grosser 
140400bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
140500bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
140600bb5a99STobias Grosser     isl_id_free(Id);
140700bb5a99STobias Grosser 
140800bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
140900bb5a99STobias Grosser       Arg++;
141000bb5a99STobias Grosser       continue;
141100bb5a99STobias Grosser     }
141200bb5a99STobias Grosser 
1413fe74a7a1STobias Grosser     Value *Val = &*Arg;
1414fe74a7a1STobias Grosser 
1415fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
141600bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1417fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1418fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1419fe74a7a1STobias Grosser     }
1420fe74a7a1STobias Grosser 
1421fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
142200bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
142300bb5a99STobias Grosser 
142400bb5a99STobias Grosser     Arg++;
142500bb5a99STobias Grosser   }
142600bb5a99STobias Grosser }
142700bb5a99STobias Grosser 
142851dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
142951dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
143051dfc275STobias Grosser   auto Arg = FN->arg_begin();
143151dfc275STobias Grosser 
143251dfc275STobias Grosser   bool StoredScalar = false;
143351dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
143451dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
143551dfc275STobias Grosser       continue;
143651dfc275STobias Grosser 
143751dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
143851dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
143951dfc275STobias Grosser     isl_id_free(Id);
144051dfc275STobias Grosser 
144151dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
144251dfc275STobias Grosser       Arg++;
144351dfc275STobias Grosser       continue;
144451dfc275STobias Grosser     }
144551dfc275STobias Grosser 
144651dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
144751dfc275STobias Grosser       Arg++;
144851dfc275STobias Grosser       continue;
144951dfc275STobias Grosser     }
145051dfc275STobias Grosser 
145151dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
145251dfc275STobias Grosser     Value *ArgPtr = &*Arg;
145351dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
145451dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
145551dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
145651dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
145751dfc275STobias Grosser     StoredScalar = true;
145851dfc275STobias Grosser 
145951dfc275STobias Grosser     Arg++;
146051dfc275STobias Grosser   }
146151dfc275STobias Grosser 
146251dfc275STobias Grosser   if (StoredScalar)
146351dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
146451dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
146551dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
146651dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
146751dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
146851dfc275STobias Grosser       BuildSuccessful = 0;
146951dfc275STobias Grosser }
147051dfc275STobias Grosser 
1471b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1472b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1473b513b491STobias Grosser 
1474b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1475b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1476b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1477b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1478b513b491STobias Grosser 
1479f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1480b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1481b513b491STobias Grosser 
1482f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1483928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1484b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1485f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1486b513b491STobias Grosser       isl_val_free(Val);
1487b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1488928d7573STobias Grosser     }
1489928d7573STobias Grosser 
1490928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1491928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1492928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1493928d7573STobias Grosser       isl_val_free(Val);
1494b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1495b513b491STobias Grosser     }
1496b513b491STobias Grosser 
1497130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1498130ca30fSTobias Grosser     Value *Allocation;
1499130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1500130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1501130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1502130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1503130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1504f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1505f919d8b3STobias Grosser 
1506130ca30fSTobias Grosser       Allocation = GlobalVar;
1507130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1508130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1509130ca30fSTobias Grosser     } else {
1510130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1511130ca30fSTobias Grosser     }
1512130ca30fSTobias Grosser     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1513130ca30fSTobias Grosser                                      ScopArrayInfo::MK_Array);
1514b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1515130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1516130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1517b513b491STobias Grosser     KernelIds.push_back(Id);
1518b513b491STobias Grosser     IDToSAI[Id] = SAI;
1519b513b491STobias Grosser   }
1520b513b491STobias Grosser }
1521b513b491STobias Grosser 
1522edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1523edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
152432837fe3STobias Grosser 
152532837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
152632837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
152732837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
152832837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
152932837fe3STobias Grosser 
1530edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
153132837fe3STobias Grosser 
153259ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
153332837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
153432837fe3STobias Grosser 
153559ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
153659ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
153759ab0705STobias Grosser 
153832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
153932837fe3STobias Grosser   Builder.CreateRetVoid();
154032837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1541472f9654STobias Grosser 
1542629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1543629109b6STobias Grosser 
154400bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1545b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1546472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
154732837fe3STobias Grosser }
154832837fe3STobias Grosser 
154974dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
155074dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
155174dc3cb4STobias Grosser   std::string ErrMsg;
155274dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
155374dc3cb4STobias Grosser 
155474dc3cb4STobias Grosser   if (!GPUTarget) {
155574dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
155674dc3cb4STobias Grosser     return "";
155774dc3cb4STobias Grosser   }
155874dc3cb4STobias Grosser 
155974dc3cb4STobias Grosser   TargetOptions Options;
156074dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
156174dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
156274dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
156374dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
156474dc3cb4STobias Grosser 
156574dc3cb4STobias Grosser   SmallString<0> ASMString;
156674dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
156774dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
156874dc3cb4STobias Grosser 
156974dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
157074dc3cb4STobias Grosser 
157174dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
157274dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
157374dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
157474dc3cb4STobias Grosser     return "";
157574dc3cb4STobias Grosser   }
157674dc3cb4STobias Grosser 
157774dc3cb4STobias Grosser   PM.run(*GPUModule);
157874dc3cb4STobias Grosser 
157974dc3cb4STobias Grosser   return ASMStream.str();
158074dc3cb4STobias Grosser }
158174dc3cb4STobias Grosser 
158257793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
15835857b701STobias Grosser   if (verifyModule(*GPUModule)) {
15845857b701STobias Grosser     BuildSuccessful = false;
15855857b701STobias Grosser     return "";
15865857b701STobias Grosser   }
158732837fe3STobias Grosser 
158832837fe3STobias Grosser   if (DumpKernelIR)
158932837fe3STobias Grosser     outs() << *GPUModule << "\n";
159032837fe3STobias Grosser 
15919a18d559STobias Grosser   // Optimize module.
15929a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
15939a18d559STobias Grosser   PassManagerBuilder PassBuilder;
15949a18d559STobias Grosser   PassBuilder.OptLevel = 3;
15959a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
15969a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
15979a18d559STobias Grosser   OptPasses.run(*GPUModule);
15989a18d559STobias Grosser 
159974dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
160074dc3cb4STobias Grosser 
160174dc3cb4STobias Grosser   if (DumpKernelASM)
160274dc3cb4STobias Grosser     outs() << Assembly << "\n";
160374dc3cb4STobias Grosser 
160432837fe3STobias Grosser   GPUModule.release();
1605472f9654STobias Grosser   KernelIDs.clear();
160657793596STobias Grosser 
160757793596STobias Grosser   return Assembly;
160832837fe3STobias Grosser }
160932837fe3STobias Grosser 
16109dfe4e7cSTobias Grosser namespace {
16119dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
16129dfe4e7cSTobias Grosser public:
16139dfe4e7cSTobias Grosser   static char ID;
16149dfe4e7cSTobias Grosser 
1615e938517eSTobias Grosser   /// The scop that is currently processed.
1616e938517eSTobias Grosser   Scop *S;
1617e938517eSTobias Grosser 
161838fc0aedSTobias Grosser   LoopInfo *LI;
161938fc0aedSTobias Grosser   DominatorTree *DT;
162038fc0aedSTobias Grosser   ScalarEvolution *SE;
162138fc0aedSTobias Grosser   const DataLayout *DL;
162238fc0aedSTobias Grosser   RegionInfo *RI;
162338fc0aedSTobias Grosser 
16249dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
16259dfe4e7cSTobias Grosser 
1626e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1627e938517eSTobias Grosser   ///
1628e938517eSTobias Grosser   /// @returns The compilation options.
1629e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1630e938517eSTobias Grosser     auto DebugOptions =
1631e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1632e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1633e938517eSTobias Grosser 
1634e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1635e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1636e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1637e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
16388950ceadSTobias Grosser     DebugOptions->verbose = false;
1639e938517eSTobias Grosser 
1640e938517eSTobias Grosser     Options->debug = DebugOptions;
1641e938517eSTobias Grosser 
1642e938517eSTobias Grosser     Options->reschedule = true;
1643e938517eSTobias Grosser     Options->scale_tile_loops = false;
1644e938517eSTobias Grosser     Options->wrap = false;
1645e938517eSTobias Grosser 
1646e938517eSTobias Grosser     Options->non_negative_parameters = false;
1647e938517eSTobias Grosser     Options->ctx = nullptr;
1648e938517eSTobias Grosser     Options->sizes = nullptr;
1649e938517eSTobias Grosser 
16504eaedde5STobias Grosser     Options->tile_size = 32;
16514eaedde5STobias Grosser 
1652130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1653b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1654b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1655e938517eSTobias Grosser 
1656e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1657e938517eSTobias Grosser     Options->openmp = false;
1658e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1659e938517eSTobias Grosser     Options->live_range_reordering = false;
1660e938517eSTobias Grosser 
1661e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1662e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1663e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1664e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1665e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1666e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1667e938517eSTobias Grosser 
1668e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1669e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1670e938517eSTobias Grosser 
1671e938517eSTobias Grosser     return Options;
1672e938517eSTobias Grosser   }
1673e938517eSTobias Grosser 
1674f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1675f384594dSTobias Grosser   ///
1676f384594dSTobias Grosser   /// Instead of a normal access of the form:
1677f384594dSTobias Grosser   ///
1678f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1679f384594dSTobias Grosser   ///
1680f384594dSTobias Grosser   /// a tagged access has the form
1681f384594dSTobias Grosser   ///
1682f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1683f384594dSTobias Grosser   ///
1684f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1685f384594dSTobias Grosser   /// triggered the access.
1686f384594dSTobias Grosser   ///
1687f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1688f384594dSTobias Grosser   ///
1689f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1690f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1691f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1692f384594dSTobias Grosser 
1693f384594dSTobias Grosser     for (auto &Stmt : *S)
1694f384594dSTobias Grosser       for (auto &Acc : Stmt)
1695f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1696f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1697f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1698f384594dSTobias Grosser 
1699f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1700f384594dSTobias Grosser           Space = isl_space_range(Space);
1701f384594dSTobias Grosser           Space = isl_space_from_range(Space);
17026293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1703f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1704f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1705f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1706f384594dSTobias Grosser         }
1707f384594dSTobias Grosser 
1708f384594dSTobias Grosser     return Accesses;
1709f384594dSTobias Grosser   }
1710f384594dSTobias Grosser 
1711f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1712f384594dSTobias Grosser   ///
1713f384594dSTobias Grosser   /// @see getTaggedAccesses
1714f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1715f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1716f384594dSTobias Grosser   }
1717f384594dSTobias Grosser 
1718f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1719f384594dSTobias Grosser   ///
1720f384594dSTobias Grosser   /// @see getTaggedAccesses
1721f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1722f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1723f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1724f384594dSTobias Grosser   }
1725f384594dSTobias Grosser 
1726f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1727f384594dSTobias Grosser   ///
1728f384594dSTobias Grosser   /// @see getTaggedAccesses
1729f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1730f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1731f384594dSTobias Grosser   }
1732f384594dSTobias Grosser 
1733aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1734aef5196fSTobias Grosser   ///
1735aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1736aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1737aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1738aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1739aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1740aef5196fSTobias Grosser   /// the data format that ppcg expects.
1741aef5196fSTobias Grosser   ///
1742aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1743aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1744aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1745bd81a7eeSTobias Grosser         S->getIslCtx(),
1746bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1747aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1748aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1749aef5196fSTobias Grosser 
1750aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1751aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1752aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1753aef5196fSTobias Grosser     }
1754aef5196fSTobias Grosser 
1755aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1756d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1757aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1758aef5196fSTobias Grosser     }
1759aef5196fSTobias Grosser 
1760aef5196fSTobias Grosser     isl_space_free(Space);
1761aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1762aef5196fSTobias Grosser 
1763aef5196fSTobias Grosser     return Names;
1764aef5196fSTobias Grosser   }
1765aef5196fSTobias Grosser 
1766e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1767e938517eSTobias Grosser   ///
1768f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1769f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1770f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1771f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1772e938517eSTobias Grosser   ///
1773e938517eSTobias Grosser   /// @returns A new ppcg scop.
1774e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1775e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1776e938517eSTobias Grosser 
1777e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1778e938517eSTobias Grosser 
1779e938517eSTobias Grosser     PPCGScop->start = 0;
1780e938517eSTobias Grosser     PPCGScop->end = 0;
1781e938517eSTobias Grosser 
1782f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1783f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1784e938517eSTobias Grosser     PPCGScop->call = nullptr;
1785f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1786f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1787e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1788f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1789f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1790f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1791f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1792e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1793f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1794e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1795e938517eSTobias Grosser 
1796e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1797e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1798e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1799e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1800e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1801e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1802e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1803e938517eSTobias Grosser 
1804f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1805aef5196fSTobias Grosser     PPCGScop->names = getNames();
1806e938517eSTobias Grosser 
1807e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1808e938517eSTobias Grosser 
1809f384594dSTobias Grosser     compute_tagger(PPCGScop);
1810f384594dSTobias Grosser     compute_dependences(PPCGScop);
1811f384594dSTobias Grosser 
1812e938517eSTobias Grosser     return PPCGScop;
1813e938517eSTobias Grosser   }
1814e938517eSTobias Grosser 
181560f63b49STobias Grosser   /// Collect the array acesses in a statement.
181660f63b49STobias Grosser   ///
181760f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
181860f63b49STobias Grosser   ///
181960f63b49STobias Grosser   /// @returns A list of array accesses.
182060f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
182160f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
182260f63b49STobias Grosser 
182360f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
182460f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
182560f63b49STobias Grosser       Access->read = Acc->isRead();
182660f63b49STobias Grosser       Access->write = Acc->isWrite();
182760f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
182860f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
182960f63b49STobias Grosser       Space = isl_space_range(Space);
183060f63b49STobias Grosser       Space = isl_space_from_range(Space);
18316293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
183260f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
183360f63b49STobias Grosser       Access->tagged_access =
183460f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1835b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
183660f63b49STobias Grosser       Access->ref_id = Acc->getId();
183760f63b49STobias Grosser       Access->next = Accesses;
1838b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
183960f63b49STobias Grosser       Accesses = Access;
184060f63b49STobias Grosser     }
184160f63b49STobias Grosser 
184260f63b49STobias Grosser     return Accesses;
184360f63b49STobias Grosser   }
184460f63b49STobias Grosser 
184569b46751STobias Grosser   /// Collect the list of GPU statements.
184669b46751STobias Grosser   ///
184769b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
184869b46751STobias Grosser   /// as well as a list with all memory accesses.
184969b46751STobias Grosser   ///
185069b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
185169b46751STobias Grosser   ///
185269b46751STobias Grosser   /// @returns A linked-list of statements.
185369b46751STobias Grosser   gpu_stmt *getStatements() {
185469b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
185569b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
185669b46751STobias Grosser 
185769b46751STobias Grosser     int i = 0;
185869b46751STobias Grosser     for (auto &Stmt : *S) {
185969b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
186069b46751STobias Grosser 
186169b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
186269b46751STobias Grosser 
186369b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
186469b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
186560f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
186669b46751STobias Grosser       i++;
186769b46751STobias Grosser     }
186869b46751STobias Grosser 
186969b46751STobias Grosser     return Stmts;
187069b46751STobias Grosser   }
187169b46751STobias Grosser 
187260f63b49STobias Grosser   /// Derive the extent of an array.
187360f63b49STobias Grosser   ///
1874d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
1875d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
1876d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
1877d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
1878d58acf86STobias Grosser   /// subscript value for the first dimension.
187960f63b49STobias Grosser   ///
188060f63b49STobias Grosser   /// @param Array The array to derive the extent for.
188160f63b49STobias Grosser   ///
188260f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
188360f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1884d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
188560f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
188660f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1887d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
188860f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1889d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1890d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1891d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1892d58acf86STobias Grosser 
1893d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
1894d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1895d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
1896d58acf86STobias Grosser     }
1897d58acf86STobias Grosser 
1898d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
1899d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1900d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
1901d58acf86STobias Grosser     }
1902d58acf86STobias Grosser 
190360f63b49STobias Grosser     isl_set *AccessSet =
190460f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
190560f63b49STobias Grosser 
1906d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
1907d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1908d58acf86STobias Grosser 
1909d58acf86STobias Grosser     isl_pw_aff *Val =
1910d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1911d58acf86STobias Grosser 
1912d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1913d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1914d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1915d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1916d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1917d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1918d58acf86STobias Grosser     OuterMin =
1919d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1920d58acf86STobias Grosser     OuterMax =
1921d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1922d58acf86STobias Grosser 
1923d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
1924d58acf86STobias Grosser 
1925d58acf86STobias Grosser     Extent = isl_set_intersect(
1926d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1927d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1928d58acf86STobias Grosser 
1929d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
1930d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1931d58acf86STobias Grosser 
1932d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
1933d58acf86STobias Grosser       isl_pw_aff *PwAff =
1934d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1935d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1936d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1937d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1938d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
1939d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1940d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1941d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1942d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
1943d58acf86STobias Grosser     }
1944d58acf86STobias Grosser 
1945d58acf86STobias Grosser     return Extent;
194660f63b49STobias Grosser   }
194760f63b49STobias Grosser 
194860f63b49STobias Grosser   /// Derive the bounds of an array.
194960f63b49STobias Grosser   ///
195060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
195160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
195260f63b49STobias Grosser   /// ScopArrayInfo.
195360f63b49STobias Grosser   ///
195460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
195560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
195660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
195760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
195802293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
195902293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
196002293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
196102293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
196202293ed7STobias Grosser         isl_set_free(Dom);
196302293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
196402293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
196502293ed7STobias Grosser       } else {
196660f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
196760f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
196860f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
196960f63b49STobias Grosser         isl_set_free(Dom);
197060f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
197102293ed7STobias Grosser         isl_local_space *LS =
197202293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
197360f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
197460f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
197560f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
197660f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
197760f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
197860f63b49STobias Grosser       }
197902293ed7STobias Grosser     }
198060f63b49STobias Grosser 
198160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
198260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
198360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
198460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
198560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
198660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
198760f63b49STobias Grosser     }
198860f63b49STobias Grosser   }
198960f63b49STobias Grosser 
199060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
199160f63b49STobias Grosser   ///
199260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
199360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
199460f63b49STobias Grosser     int i = 0;
1995d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
199660f63b49STobias Grosser       std::string TypeName;
199760f63b49STobias Grosser       raw_string_ostream OS(TypeName);
199860f63b49STobias Grosser 
199960f63b49STobias Grosser       OS << *Array->getElementType();
200060f63b49STobias Grosser       TypeName = OS.str();
200160f63b49STobias Grosser 
200260f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
200360f63b49STobias Grosser 
200460f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
200560f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
200660f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
200760f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
200860f63b49STobias Grosser       PPCGArray.extent = nullptr;
200960f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
201060f63b49STobias Grosser       PPCGArray.bound =
201160f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
201260f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
201360f63b49STobias Grosser       PPCGArray.n_ref = 0;
201460f63b49STobias Grosser       PPCGArray.refs = nullptr;
201560f63b49STobias Grosser       PPCGArray.accessed = true;
2016fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2017fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
201860f63b49STobias Grosser       PPCGArray.has_compound_element = false;
201960f63b49STobias Grosser       PPCGArray.local = false;
202060f63b49STobias Grosser       PPCGArray.declare_local = false;
202160f63b49STobias Grosser       PPCGArray.global = false;
202260f63b49STobias Grosser       PPCGArray.linearize = false;
202360f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
202413c78e4dSTobias Grosser       PPCGArray.user = Array;
202560f63b49STobias Grosser 
202660f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
20272d010dafSTobias Grosser       i++;
2028b9fc860aSTobias Grosser 
2029b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
203060f63b49STobias Grosser     }
203160f63b49STobias Grosser   }
203260f63b49STobias Grosser 
203360f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
203460f63b49STobias Grosser   ///
203560f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
203660f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
203760f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
203860f63b49STobias Grosser 
2039d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
204060f63b49STobias Grosser       isl_space *Space = Array->getSpace();
204160f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
204260f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
204360f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
204460f63b49STobias Grosser     }
204560f63b49STobias Grosser 
204660f63b49STobias Grosser     return Maps;
204760f63b49STobias Grosser   }
204860f63b49STobias Grosser 
2049e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2050e938517eSTobias Grosser   ///
2051e938517eSTobias Grosser   /// @returns A new gpu grogram description.
2052e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2053e938517eSTobias Grosser 
2054e938517eSTobias Grosser     if (!PPCGScop)
2055e938517eSTobias Grosser       return nullptr;
2056e938517eSTobias Grosser 
2057e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2058e938517eSTobias Grosser 
2059e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2060e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2061aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
206260f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
206360f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
206460f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
206560f63b49STobias Grosser     PPCGProg->tagged_must_kill =
206660f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
206760f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
206860f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2069e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2070e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
207169b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
207269b46751STobias Grosser     PPCGProg->stmts = getStatements();
207360f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
207460f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
207560f63b49STobias Grosser                                        PPCGProg->n_array);
207660f63b49STobias Grosser 
207760f63b49STobias Grosser     createArrays(PPCGProg);
2078e938517eSTobias Grosser 
2079d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2080d58acf86STobias Grosser 
2081e938517eSTobias Grosser     return PPCGProg;
2082e938517eSTobias Grosser   }
2083e938517eSTobias Grosser 
208469b46751STobias Grosser   struct PrintGPUUserData {
208569b46751STobias Grosser     struct cuda_info *CudaInfo;
208669b46751STobias Grosser     struct gpu_prog *PPCGProg;
208769b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
208869b46751STobias Grosser   };
208969b46751STobias Grosser 
209069b46751STobias Grosser   /// Print a user statement node in the host code.
209169b46751STobias Grosser   ///
209269b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
209369b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
209469b46751STobias Grosser   /// host ast.
209569b46751STobias Grosser   ///
209669b46751STobias Grosser   /// @param P The printer to print to
209769b46751STobias Grosser   /// @param Options The printing options to use
209869b46751STobias Grosser   /// @param Node The node to print
209969b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
210069b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
210169b46751STobias Grosser   ///
210269b46751STobias Grosser   /// @returns A printer to which the output has been printed.
210369b46751STobias Grosser   static __isl_give isl_printer *
210469b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
210569b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
210669b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
210769b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
210869b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
210969b46751STobias Grosser 
211069b46751STobias Grosser     if (Id) {
211120251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
211220251734STobias Grosser 
211320251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
211420251734STobias Grosser       // otherwise try to call pet functionality that is not available in
211520251734STobias Grosser       // Polly.
211620251734STobias Grosser       if (IsUser) {
211720251734STobias Grosser         P = isl_printer_start_line(P);
211820251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
211920251734STobias Grosser         P = isl_printer_end_line(P);
212020251734STobias Grosser         isl_id_free(Id);
212120251734STobias Grosser         isl_ast_print_options_free(Options);
212220251734STobias Grosser         return P;
212320251734STobias Grosser       }
212420251734STobias Grosser 
212569b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
212669b46751STobias Grosser       isl_id_free(Id);
212769b46751STobias Grosser       Data->Kernels.push_back(Kernel);
212869b46751STobias Grosser     }
212969b46751STobias Grosser 
213069b46751STobias Grosser     return print_host_user(P, Options, Node, User);
213169b46751STobias Grosser   }
213269b46751STobias Grosser 
213369b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
213469b46751STobias Grosser   ///
213569b46751STobias Grosser   /// @param Kernel The kernel to print
213669b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
213769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
213869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
213969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
214069b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
214169b46751STobias Grosser     char *String = isl_printer_get_str(P);
214269b46751STobias Grosser     printf("%s\n", String);
214369b46751STobias Grosser     free(String);
214469b46751STobias Grosser     isl_printer_free(P);
214569b46751STobias Grosser   }
214669b46751STobias Grosser 
214769b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
214869b46751STobias Grosser   ///
214969b46751STobias Grosser   /// @param Tree An AST describing GPU code
215069b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
215169b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
215269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
215369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
215469b46751STobias Grosser 
215569b46751STobias Grosser     PrintGPUUserData Data;
215669b46751STobias Grosser     Data.PPCGProg = PPCGProg;
215769b46751STobias Grosser 
215869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
215969b46751STobias Grosser     Options =
216069b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
216169b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
216269b46751STobias Grosser     char *String = isl_printer_get_str(P);
216369b46751STobias Grosser     printf("# host\n");
216469b46751STobias Grosser     printf("%s\n", String);
216569b46751STobias Grosser     free(String);
216669b46751STobias Grosser     isl_printer_free(P);
216769b46751STobias Grosser 
216869b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
216969b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
217069b46751STobias Grosser       printKernel(Kernel);
217169b46751STobias Grosser     }
217269b46751STobias Grosser   }
217369b46751STobias Grosser 
2174f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2175f384594dSTobias Grosser   //
2176f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2177f384594dSTobias Grosser   //
2178f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2179f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2180f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2181f384594dSTobias Grosser   //
2182f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2183f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2184f384594dSTobias Grosser   // strategy directly from this pass.
2185f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2186f384594dSTobias Grosser 
2187f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2188f384594dSTobias Grosser 
2189f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2190f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2191f384594dSTobias Grosser     PPCGGen->print = nullptr;
2192f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
219360c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2194f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2195f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2196f384594dSTobias Grosser     PPCGGen->types.n = 0;
2197f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2198f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2199f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2200f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2201f384594dSTobias Grosser 
2202f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2203f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2204f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
22052341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2206f384594dSTobias Grosser 
2207f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2208f384594dSTobias Grosser 
2209aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2210aef5196fSTobias Grosser 
221169b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2212aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
221369b46751STobias Grosser     } else {
2214aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
221569b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
221669b46751STobias Grosser     }
2217aef5196fSTobias Grosser 
2218f384594dSTobias Grosser     if (DumpSchedule) {
2219f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2220f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2221f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2222f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2223f384594dSTobias Grosser       if (Schedule)
2224f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2225f384594dSTobias Grosser       else
2226f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2227f384594dSTobias Grosser 
2228f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2229f384594dSTobias Grosser       isl_printer_free(P);
2230f384594dSTobias Grosser     }
2231f384594dSTobias Grosser 
223269b46751STobias Grosser     if (DumpCode) {
223369b46751STobias Grosser       printf("Code\n");
223469b46751STobias Grosser       printf("====\n");
223569b46751STobias Grosser       if (PPCGGen->tree)
223669b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
223769b46751STobias Grosser       else
223869b46751STobias Grosser         printf("No code generated\n");
223969b46751STobias Grosser     }
224069b46751STobias Grosser 
2241f384594dSTobias Grosser     isl_schedule_free(Schedule);
2242f384594dSTobias Grosser 
2243f384594dSTobias Grosser     return PPCGGen;
2244f384594dSTobias Grosser   }
2245f384594dSTobias Grosser 
2246f384594dSTobias Grosser   /// Free gpu_gen structure.
2247f384594dSTobias Grosser   ///
2248f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2249f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2250f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2251f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2252f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2253f384594dSTobias Grosser     free(PPCGGen);
2254f384594dSTobias Grosser   }
2255f384594dSTobias Grosser 
2256b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2257b307ed4dSTobias Grosser   ///
2258b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2259b307ed4dSTobias Grosser   /// ourselves.
2260b307ed4dSTobias Grosser   ///
2261b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2262b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2263b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2264b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2265b307ed4dSTobias Grosser     free(PPCGScop->options);
2266b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2267b307ed4dSTobias Grosser   }
2268b307ed4dSTobias Grosser 
2269*82f2af35STobias Grosser   /// Approximate the number of points in the set.
2270*82f2af35STobias Grosser   ///
2271*82f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
2272*82f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
2273*82f2af35STobias Grosser   ///
2274*82f2af35STobias Grosser   /// @param Set   The set to count.
2275*82f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
2276*82f2af35STobias Grosser   ///              expression.
2277*82f2af35STobias Grosser   ///
2278*82f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
2279*82f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
2280*82f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
2281*82f2af35STobias Grosser 
2282*82f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
2283*82f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
2284*82f2af35STobias Grosser 
2285*82f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
2286*82f2af35STobias Grosser     Space = isl_space_params(Space);
2287*82f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
2288*82f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
2289*82f2af35STobias Grosser 
2290*82f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
2291*82f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
2292*82f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
2293*82f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
2294*82f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
2295*82f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
2296*82f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
2297*82f2af35STobias Grosser     }
2298*82f2af35STobias Grosser 
2299*82f2af35STobias Grosser     isl_set_free(Set);
2300*82f2af35STobias Grosser     isl_pw_aff_free(OneAff);
2301*82f2af35STobias Grosser 
2302*82f2af35STobias Grosser     return Expr;
2303*82f2af35STobias Grosser   }
2304*82f2af35STobias Grosser 
2305*82f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
2306*82f2af35STobias Grosser   /// statement.
2307*82f2af35STobias Grosser   ///
2308*82f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
2309*82f2af35STobias Grosser   ///              instructions.
2310*82f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
2311*82f2af35STobias Grosser   ///              expression.
2312*82f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
2313*82f2af35STobias Grosser   ///          by @p Stmt.
2314*82f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
2315*82f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
2316*82f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
2317*82f2af35STobias Grosser 
2318*82f2af35STobias Grosser     long InstCount = 0;
2319*82f2af35STobias Grosser 
2320*82f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
2321*82f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
2322*82f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
2323*82f2af35STobias Grosser     } else {
2324*82f2af35STobias Grosser       auto *R = Stmt.getRegion();
2325*82f2af35STobias Grosser 
2326*82f2af35STobias Grosser       for (auto *BB : R->blocks()) {
2327*82f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
2328*82f2af35STobias Grosser       }
2329*82f2af35STobias Grosser     }
2330*82f2af35STobias Grosser 
2331*82f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
2332*82f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
2333*82f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
2334*82f2af35STobias Grosser   }
2335*82f2af35STobias Grosser 
2336*82f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
2337*82f2af35STobias Grosser   ///
2338*82f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
2339*82f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
2340*82f2af35STobias Grosser   ///              expression.
2341*82f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
2342*82f2af35STobias Grosser   ///          in @p S.
2343*82f2af35STobias Grosser   __isl_give isl_ast_expr *
2344*82f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
2345*82f2af35STobias Grosser     isl_ast_expr *Instructions;
2346*82f2af35STobias Grosser 
2347*82f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
2348*82f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
2349*82f2af35STobias Grosser 
2350*82f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
2351*82f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
2352*82f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
2353*82f2af35STobias Grosser     }
2354*82f2af35STobias Grosser     return Instructions;
2355*82f2af35STobias Grosser   }
2356*82f2af35STobias Grosser 
2357*82f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
2358*82f2af35STobias Grosser   ///
2359*82f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
2360*82f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
2361*82f2af35STobias Grosser   ///              expression.
2362*82f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
2363*82f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
2364*82f2af35STobias Grosser   __isl_give isl_ast_expr *
2365*82f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
2366*82f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
2367*82f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
2368*82f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
2369*82f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
2370*82f2af35STobias Grosser   }
2371*82f2af35STobias Grosser 
237238fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
237338fc0aedSTobias Grosser   ///
237432837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
237532837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
237632837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
237738fc0aedSTobias Grosser     ScopAnnotator Annotator;
237838fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
237938fc0aedSTobias Grosser 
238038fc0aedSTobias Grosser     Region *R = &S->getRegion();
238138fc0aedSTobias Grosser 
238238fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
238338fc0aedSTobias Grosser 
238438fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
238538fc0aedSTobias Grosser 
238638fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
238738fc0aedSTobias Grosser 
238832837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
238932837fe3STobias Grosser                                Prog);
239038fc0aedSTobias Grosser 
239138fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
239238fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
239338fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
239438fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
239538fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
239638fc0aedSTobias Grosser     // code generating this scop.
239738fc0aedSTobias Grosser     BasicBlock *StartBlock =
239838fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
239938fc0aedSTobias Grosser 
240038fc0aedSTobias Grosser     // TODO: Handle LICM
240138fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
240238fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
240338fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2404cb1aef8dSTobias Grosser 
2405cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2406cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2407*82f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
2408*82f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2409cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2410cb1aef8dSTobias Grosser 
2411cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2412cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2413cb1aef8dSTobias Grosser 
241438fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2415fa7b0802STobias Grosser 
2416fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
241738fc0aedSTobias Grosser     NodeBuilder.create(Root);
24188ed5e599STobias Grosser     NodeBuilder.finalize();
24195857b701STobias Grosser 
24205857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
24215857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
242238fc0aedSTobias Grosser   }
242338fc0aedSTobias Grosser 
2424e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2425e938517eSTobias Grosser     S = &CurrentScop;
242638fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
242738fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
242838fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
242938fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
243038fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2431e938517eSTobias Grosser 
24322d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
24332d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
24342d58a64eSTobias Grosser       return false;
24352d58a64eSTobias Grosser 
2436e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2437e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2438f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
243938fc0aedSTobias Grosser 
244038fc0aedSTobias Grosser     if (PPCGGen->tree)
244132837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
244238fc0aedSTobias Grosser 
2443b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2444f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2445e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2446e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2447e938517eSTobias Grosser 
2448e938517eSTobias Grosser     return true;
2449e938517eSTobias Grosser   }
24509dfe4e7cSTobias Grosser 
24519dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
24529dfe4e7cSTobias Grosser 
24539dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
24549dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
24559dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
24569dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
24579dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
24589dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
24599dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
24609dfe4e7cSTobias Grosser 
24619dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
24629dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
24639dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
24649dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
24659dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
24669dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
24679dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
24689dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
24699dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
24709dfe4e7cSTobias Grosser 
24719dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
24729dfe4e7cSTobias Grosser     //        region tree.
24739dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
24749dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
24759dfe4e7cSTobias Grosser   }
24769dfe4e7cSTobias Grosser };
24779dfe4e7cSTobias Grosser }
24789dfe4e7cSTobias Grosser 
24799dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
24809dfe4e7cSTobias Grosser 
24819dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
24829dfe4e7cSTobias Grosser 
24839dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
24849dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
24859dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
24869dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
24879dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
24889dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
24899dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
24909dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
24919dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
24929dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2493