19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
15cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
169dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1738fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
189dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
199dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
20f384594dSTobias Grosser #include "polly/Options.h"
21629109b6STobias Grosser #include "polly/ScopDetection.h"
229dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
23edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2474dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
399dfe4e7cSTobias Grosser 
40f384594dSTobias Grosser #include "isl/union_map.h"
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
48e938517eSTobias Grosser }
49e938517eSTobias Grosser 
509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser using namespace polly;
539dfe4e7cSTobias Grosser using namespace llvm;
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
569dfe4e7cSTobias Grosser 
57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
58f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
59681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
60f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6169b46751STobias Grosser 
6269b46751STobias Grosser static cl::opt<bool>
6369b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6469b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6569b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6669b46751STobias Grosser 
6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6832837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6932837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7032837fe3STobias Grosser                                   cl::cat(PollyCategory));
7132837fe3STobias Grosser 
7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7374dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7474dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7574dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7674dc3cb4STobias Grosser 
7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7874dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7974dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8074dc3cb4STobias Grosser                               cl::cat(PollyCategory));
81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
82b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
83b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
84b513b491STobias Grosser                                   cl::cat(PollyCategory));
85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
86130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
87130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
88130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8974dc3cb4STobias Grosser 
9074dc3cb4STobias Grosser static cl::opt<std::string>
9174dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9274dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
9374dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
9474dc3cb4STobias Grosser 
9560c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
9660c60025STobias Grosser ///
9760c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
9860c60025STobias Grosser /// of the scheduled ScopStmts.
9960c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
100edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
10160c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
10260c60025STobias Grosser                                        isl_id *Id, void *User),
10360c60025STobias Grosser     void *UserIndex,
10460c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
105edb885cbSTobias Grosser     void *UserExpr) {
10660c60025STobias Grosser 
107edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
10860c60025STobias Grosser 
109edb885cbSTobias Grosser   isl_ctx *Ctx;
110edb885cbSTobias Grosser 
111edb885cbSTobias Grosser   if (!Stmt || !Build)
112edb885cbSTobias Grosser     return NULL;
113edb885cbSTobias Grosser 
114edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
115edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
116edb885cbSTobias Grosser 
117edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
118edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
119edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
120edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
121edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
122edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
123edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
124edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
125edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
126edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
127edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
128edb885cbSTobias Grosser   }
129edb885cbSTobias Grosser 
130edb885cbSTobias Grosser   return RefToExpr;
13160c60025STobias Grosser }
132f384594dSTobias Grosser 
13338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
13438fc0aedSTobias Grosser ///
13538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
13638fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
13738fc0aedSTobias Grosser /// for generating GPU specific user nodes.
13838fc0aedSTobias Grosser ///
13938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
14038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
14138fc0aedSTobias Grosser public:
14238fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
14338fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
14432837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
145edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
146edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
147edb885cbSTobias Grosser   }
14838fc0aedSTobias Grosser 
149fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
150fa7b0802STobias Grosser   void initializeAfterRTH();
151fa7b0802STobias Grosser 
152fa7b0802STobias Grosser   /// Finalize the generated scop.
153fa7b0802STobias Grosser   virtual void finalize();
154fa7b0802STobias Grosser 
1555857b701STobias Grosser   /// Track if the full build process was successful.
1565857b701STobias Grosser   ///
1575857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1585857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1595857b701STobias Grosser   bool BuildSuccessful = true;
1605857b701STobias Grosser 
16138fc0aedSTobias Grosser private:
16274dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
16374dc3cb4STobias Grosser   ///
16474dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
16574dc3cb4STobias Grosser   /// more.
16674dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
16774dc3cb4STobias Grosser 
16813c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
16913c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1707287aeddSTobias Grosser 
171fa7b0802STobias Grosser   /// The current GPU context.
172fa7b0802STobias Grosser   Value *GPUContext;
173fa7b0802STobias Grosser 
174b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
175b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
176b513b491STobias Grosser 
17732837fe3STobias Grosser   /// A module containing GPU code.
17832837fe3STobias Grosser   ///
17932837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
18032837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
18132837fe3STobias Grosser 
18232837fe3STobias Grosser   /// The GPU program we generate code for.
18332837fe3STobias Grosser   gpu_prog *Prog;
18432837fe3STobias Grosser 
185472f9654STobias Grosser   /// Class to free isl_ids.
186472f9654STobias Grosser   class IslIdDeleter {
187472f9654STobias Grosser   public:
188472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
189472f9654STobias Grosser   };
190472f9654STobias Grosser 
191472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
192472f9654STobias Grosser   ///
193472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
194472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
195472f9654STobias Grosser 
196edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
197edb885cbSTobias Grosser 
19838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
19938fc0aedSTobias Grosser   ///
20038fc0aedSTobias Grosser   /// These AST nodes can be of type:
20138fc0aedSTobias Grosser   ///
20238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
20338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
20413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2055260c041STobias Grosser   ///   - In-kernel synchronization
2065260c041STobias Grosser   ///   - In-kernel memory copy statement
20738fc0aedSTobias Grosser   ///
2081fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2091fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
21032837fe3STobias Grosser 
21113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
21213c78e4dSTobias Grosser 
21313c78e4dSTobias Grosser   /// Create code for a data transfer statement
21413c78e4dSTobias Grosser   ///
21513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
21613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
21713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
21813c78e4dSTobias Grosser                           enum DataDirection Direction);
21913c78e4dSTobias Grosser 
220edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
221edb885cbSTobias Grosser   ///
222edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
223edb885cbSTobias Grosser   ///
224edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
225edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
226edb885cbSTobias Grosser 
22779a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
22879a947c2STobias Grosser   ///
22979a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
23079a947c2STobias Grosser   ///
23179a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
23279a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
23379a947c2STobias Grosser 
23479a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
23579a947c2STobias Grosser   ///
23679a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
23779a947c2STobias Grosser   ///
23879a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
23979a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
24079a947c2STobias Grosser 
24179a947c2STobias Grosser   /// Create kernel launch parameters.
24279a947c2STobias Grosser   ///
24379a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
24479a947c2STobias Grosser   /// @param F             The kernel function that has been created.
24557693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
24679a947c2STobias Grosser   ///
24779a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
24879a947c2STobias Grosser   ///          values that are passed to the kernel.
24957693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
25057693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
25179a947c2STobias Grosser 
252b513b491STobias Grosser   /// Create declarations for kernel variable.
253b513b491STobias Grosser   ///
254b513b491STobias Grosser   /// This includes shared memory declarations.
255b513b491STobias Grosser   ///
256b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
257b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
258b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
259b513b491STobias Grosser 
260c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
261c1c6a2a6STobias Grosser   ///
262c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
263c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
264c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
265c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
266c1c6a2a6STobias Grosser   /// as specified here.
267c1c6a2a6STobias Grosser   ///
268c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
269c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
270c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
271c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
272c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
273c1c6a2a6STobias Grosser                           Value *BlockDimZ);
274c1c6a2a6STobias Grosser 
27532837fe3STobias Grosser   /// Create GPU kernel.
27632837fe3STobias Grosser   ///
27732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
27832837fe3STobias Grosser   ///
27932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
28032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
28132837fe3STobias Grosser 
28213c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
28313c78e4dSTobias Grosser   ///
28413c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
28513c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
28613c78e4dSTobias Grosser 
287*aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
288*aaabbbf8STobias Grosser   ///
289*aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
290*aaabbbf8STobias Grosser   ///
291*aaabbbf8STobias Grosser   /// Example:
292*aaabbbf8STobias Grosser   ///
293*aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
294*aaabbbf8STobias Grosser   ///     A[i + 42] += ...
295*aaabbbf8STobias Grosser   ///
296*aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
297*aaabbbf8STobias Grosser   ///
298*aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
299*aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
300*aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
301*aaabbbf8STobias Grosser 
30200bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
30300bb5a99STobias Grosser   ///
30400bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
30500bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
30600bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
30700bb5a99STobias Grosser 
30832837fe3STobias Grosser   /// Create kernel function.
30932837fe3STobias Grosser   ///
31032837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
31132837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
31232837fe3STobias Grosser   /// start block of this newly created function.
31332837fe3STobias Grosser   ///
31432837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
315edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
316edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
317edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
31832837fe3STobias Grosser 
31932837fe3STobias Grosser   /// Create the declaration of a kernel function.
32032837fe3STobias Grosser   ///
32132837fe3STobias Grosser   /// The kernel function takes as arguments:
32232837fe3STobias Grosser   ///
32332837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
324f6044bd0STobias Grosser   ///   - Host iterators
325c84a1995STobias Grosser   ///   - Parameters
32632837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
32732837fe3STobias Grosser   ///
32832837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
329edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
330edb885cbSTobias Grosser   ///
33132837fe3STobias Grosser   /// @returns The newly declared function.
332edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
333edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
33432837fe3STobias Grosser 
335472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
336472f9654STobias Grosser   ///
337472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
338472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
339472f9654STobias Grosser 
340b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
341b513b491STobias Grosser   ///
342b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
343b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
344b513b491STobias Grosser 
345edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
346edb885cbSTobias Grosser   ///
347edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
348edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
349edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
350edb885cbSTobias Grosser 
3515260c041STobias Grosser   /// Create an in-kernel synchronization call.
3525260c041STobias Grosser   void createKernelSync();
3535260c041STobias Grosser 
35474dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
35574dc3cb4STobias Grosser   ///
35674dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
35774dc3cb4STobias Grosser   std::string createKernelASM();
35874dc3cb4STobias Grosser 
35974dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
36074dc3cb4STobias Grosser   ///
36174dc3cb4STobias Grosser   /// @param F The function to remove references to.
36274dc3cb4STobias Grosser   void clearDominators(Function *F);
36374dc3cb4STobias Grosser 
36474dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
36574dc3cb4STobias Grosser   ///
36674dc3cb4STobias Grosser   /// @param F The function to remove references to.
36774dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
36874dc3cb4STobias Grosser 
36974dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
37074dc3cb4STobias Grosser   ///
37174dc3cb4STobias Grosser   /// @param F The function to remove references to.
37274dc3cb4STobias Grosser   void clearLoops(Function *F);
37374dc3cb4STobias Grosser 
37432837fe3STobias Grosser   /// Finalize the generation of the kernel function.
37532837fe3STobias Grosser   ///
37632837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
37732837fe3STobias Grosser   /// dump its IR to stderr.
37857793596STobias Grosser   ///
37957793596STobias Grosser   /// @returns The Assembly string of the kernel.
38057793596STobias Grosser   std::string finalizeKernelFunction();
381fa7b0802STobias Grosser 
3827287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
383fa7b0802STobias Grosser   void allocateDeviceArrays();
384fa7b0802STobias Grosser 
3857287aeddSTobias Grosser   /// Free all allocated device arrays.
3867287aeddSTobias Grosser   void freeDeviceArrays();
3877287aeddSTobias Grosser 
388fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
389fa7b0802STobias Grosser   ///
390fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
391fa7b0802STobias Grosser   Value *createCallInitContext();
392fa7b0802STobias Grosser 
39379a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
39479a947c2STobias Grosser   ///
39579a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
39679a947c2STobias Grosser   ///
39779a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
39879a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
39979a947c2STobias Grosser 
400fa7b0802STobias Grosser   /// Create a call to free the GPU context.
401fa7b0802STobias Grosser   ///
402fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
403fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
404fa7b0802STobias Grosser 
4057287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4067287aeddSTobias Grosser   ///
4077287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4087287aeddSTobias Grosser   ///
4097287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
410fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4117287aeddSTobias Grosser 
4127287aeddSTobias Grosser   /// Create a call to free a device array.
4137287aeddSTobias Grosser   ///
4147287aeddSTobias Grosser   /// @param Array The device array to free.
4157287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
41613c78e4dSTobias Grosser 
41713c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
41813c78e4dSTobias Grosser   ///
41913c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
42013c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
42113c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
42213c78e4dSTobias Grosser                                       Value *Size);
42313c78e4dSTobias Grosser 
42413c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
42513c78e4dSTobias Grosser   ///
42613c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
42713c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
42813c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
42913c78e4dSTobias Grosser                                       Value *Size);
43057793596STobias Grosser 
43157793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
43257793596STobias Grosser   ///
43357793596STobias Grosser   /// @param Buffer The string describing the kernel.
43457793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
43557793596STobias Grosser   ///
43657793596STobias Grosser   /// @returns A pointer to a kernel object
43757793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
43857793596STobias Grosser 
43957793596STobias Grosser   /// Create a call to free a GPU kernel.
44057793596STobias Grosser   ///
44157793596STobias Grosser   /// @param GPUKernel THe kernel to free.
44257793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
44379a947c2STobias Grosser 
44479a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
44579a947c2STobias Grosser   ///
44679a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
44779a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
44879a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
44979a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
45079a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
45179a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
45279a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
45379a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
45479a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
45579a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
45679a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
45779a947c2STobias Grosser                               Value *Parameters);
4581fb9b64dSTobias Grosser };
4591fb9b64dSTobias Grosser 
460fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
461750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
462750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
463750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
464750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
465750160e2STobias Grosser 
466fa7b0802STobias Grosser   GPUContext = createCallInitContext();
467fa7b0802STobias Grosser   allocateDeviceArrays();
468fa7b0802STobias Grosser }
469fa7b0802STobias Grosser 
470fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4717287aeddSTobias Grosser   freeDeviceArrays();
472fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
473fa7b0802STobias Grosser   IslNodeBuilder::finalize();
474fa7b0802STobias Grosser }
475fa7b0802STobias Grosser 
476fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
477fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
478fa7b0802STobias Grosser 
479fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
480fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
48113c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4827287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4837287aeddSTobias Grosser     DevArrayName.append(Array->name);
484fa7b0802STobias Grosser 
48513c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
486*aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
487*aaabbbf8STobias Grosser     if (Offset)
488*aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
489*aaabbbf8STobias Grosser           ArraySize,
490*aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
491*aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
4927287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4937287aeddSTobias Grosser     DevArray->setName(DevArrayName);
49413c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
495fa7b0802STobias Grosser   }
496fa7b0802STobias Grosser 
497fa7b0802STobias Grosser   isl_ast_build_free(Build);
498fa7b0802STobias Grosser }
499fa7b0802STobias Grosser 
500c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
501c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
502c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
503c1c6a2a6STobias Grosser 
504c1c6a2a6STobias Grosser   for (auto &F : *M) {
505c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
506c1c6a2a6STobias Grosser       continue;
507c1c6a2a6STobias Grosser 
508c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
509c1c6a2a6STobias Grosser 
510c1c6a2a6STobias Grosser     Metadata *Elements[] = {
511c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
512c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
513c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
514c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
515c1c6a2a6STobias Grosser     };
516c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
517c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
518c1c6a2a6STobias Grosser   }
519c1c6a2a6STobias Grosser }
520c1c6a2a6STobias Grosser 
5217287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
52213c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
52313c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
5247287aeddSTobias Grosser }
5257287aeddSTobias Grosser 
52657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
52757793596STobias Grosser   const char *Name = "polly_getKernel";
52857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
52957793596STobias Grosser   Function *F = M->getFunction(Name);
53057793596STobias Grosser 
53157793596STobias Grosser   // If F is not available, declare it.
53257793596STobias Grosser   if (!F) {
53357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
53457793596STobias Grosser     std::vector<Type *> Args;
53557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
53657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
53757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
53857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
53957793596STobias Grosser   }
54057793596STobias Grosser 
54157793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
54257793596STobias Grosser }
54357793596STobias Grosser 
54479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
54579a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
54679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
54779a947c2STobias Grosser   Function *F = M->getFunction(Name);
54879a947c2STobias Grosser 
54979a947c2STobias Grosser   // If F is not available, declare it.
55079a947c2STobias Grosser   if (!F) {
55179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
55279a947c2STobias Grosser     std::vector<Type *> Args;
55379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
55479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
55579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
55679a947c2STobias Grosser   }
55779a947c2STobias Grosser 
55879a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
55979a947c2STobias Grosser }
56079a947c2STobias Grosser 
56179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
56279a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
56379a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
56479a947c2STobias Grosser                                             Value *Parameters) {
56579a947c2STobias Grosser   const char *Name = "polly_launchKernel";
56679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
56779a947c2STobias Grosser   Function *F = M->getFunction(Name);
56879a947c2STobias Grosser 
56979a947c2STobias Grosser   // If F is not available, declare it.
57079a947c2STobias Grosser   if (!F) {
57179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57279a947c2STobias Grosser     std::vector<Type *> Args;
57379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
57979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
58079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
58179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
58279a947c2STobias Grosser   }
58379a947c2STobias Grosser 
58479a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
58579a947c2STobias Grosser                          BlockDimZ, Parameters});
58679a947c2STobias Grosser }
58779a947c2STobias Grosser 
58857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
58957793596STobias Grosser   const char *Name = "polly_freeKernel";
59057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
59157793596STobias Grosser   Function *F = M->getFunction(Name);
59257793596STobias Grosser 
59357793596STobias Grosser   // If F is not available, declare it.
59457793596STobias Grosser   if (!F) {
59557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
59657793596STobias Grosser     std::vector<Type *> Args;
59757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
59957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
60057793596STobias Grosser   }
60157793596STobias Grosser 
60257793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
60357793596STobias Grosser }
60457793596STobias Grosser 
6057287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
6067287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
6077287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6087287aeddSTobias Grosser   Function *F = M->getFunction(Name);
6097287aeddSTobias Grosser 
6107287aeddSTobias Grosser   // If F is not available, declare it.
6117287aeddSTobias Grosser   if (!F) {
6127287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
6137287aeddSTobias Grosser     std::vector<Type *> Args;
6147287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
6157287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
6167287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
6177287aeddSTobias Grosser   }
6187287aeddSTobias Grosser 
6197287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
6207287aeddSTobias Grosser }
6217287aeddSTobias Grosser 
622fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
623fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
624fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
625fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
626fa7b0802STobias Grosser 
627fa7b0802STobias Grosser   // If F is not available, declare it.
628fa7b0802STobias Grosser   if (!F) {
629fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
630fa7b0802STobias Grosser     std::vector<Type *> Args;
631fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
632fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
633fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
634fa7b0802STobias Grosser   }
635fa7b0802STobias Grosser 
636fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
637fa7b0802STobias Grosser }
638fa7b0802STobias Grosser 
63913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
64013c78e4dSTobias Grosser                                                     Value *DeviceData,
64113c78e4dSTobias Grosser                                                     Value *Size) {
64213c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
64313c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
64413c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
64513c78e4dSTobias Grosser 
64613c78e4dSTobias Grosser   // If F is not available, declare it.
64713c78e4dSTobias Grosser   if (!F) {
64813c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
64913c78e4dSTobias Grosser     std::vector<Type *> Args;
65013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65213c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
65313c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
65413c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
65513c78e4dSTobias Grosser   }
65613c78e4dSTobias Grosser 
65713c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
65813c78e4dSTobias Grosser }
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
66113c78e4dSTobias Grosser                                                     Value *HostData,
66213c78e4dSTobias Grosser                                                     Value *Size) {
66313c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
66413c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
66513c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
66613c78e4dSTobias Grosser 
66713c78e4dSTobias Grosser   // If F is not available, declare it.
66813c78e4dSTobias Grosser   if (!F) {
66913c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
67013c78e4dSTobias Grosser     std::vector<Type *> Args;
67113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67313c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
67413c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
67513c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
67613c78e4dSTobias Grosser   }
67713c78e4dSTobias Grosser 
67813c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
67913c78e4dSTobias Grosser }
68013c78e4dSTobias Grosser 
681fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
682fa7b0802STobias Grosser   const char *Name = "polly_initContext";
683fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
684fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
685fa7b0802STobias Grosser 
686fa7b0802STobias Grosser   // If F is not available, declare it.
687fa7b0802STobias Grosser   if (!F) {
688fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
689fa7b0802STobias Grosser     std::vector<Type *> Args;
690fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
691fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
692fa7b0802STobias Grosser   }
693fa7b0802STobias Grosser 
694fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
695fa7b0802STobias Grosser }
696fa7b0802STobias Grosser 
697fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
698fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
699fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
700fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
701fa7b0802STobias Grosser 
702fa7b0802STobias Grosser   // If F is not available, declare it.
703fa7b0802STobias Grosser   if (!F) {
704fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
705fa7b0802STobias Grosser     std::vector<Type *> Args;
706fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
707fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
708fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
709fa7b0802STobias Grosser   }
710fa7b0802STobias Grosser 
711fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
712fa7b0802STobias Grosser }
713fa7b0802STobias Grosser 
7145260c041STobias Grosser /// Check if one string is a prefix of another.
7155260c041STobias Grosser ///
7165260c041STobias Grosser /// @param String The string in which to look for the prefix.
7175260c041STobias Grosser /// @param Prefix The prefix to look for.
7185260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
7195260c041STobias Grosser   return String.find(Prefix) == 0;
7205260c041STobias Grosser }
7215260c041STobias Grosser 
72213c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
72313c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
72413c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
72513c78e4dSTobias Grosser 
72613c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
72713c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
72813c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
72913c78e4dSTobias Grosser 
73013c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
73113c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
73213c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
73313c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
73413c78e4dSTobias Grosser     }
73513c78e4dSTobias Grosser 
73613c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
737b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
738b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
73913c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
74013c78e4dSTobias Grosser   }
74113c78e4dSTobias Grosser   isl_ast_build_free(Build);
74213c78e4dSTobias Grosser   return ArraySize;
74313c78e4dSTobias Grosser }
74413c78e4dSTobias Grosser 
745*aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
746*aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
747*aaabbbf8STobias Grosser     return nullptr;
748*aaabbbf8STobias Grosser 
749*aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
750*aaabbbf8STobias Grosser 
751*aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
752*aaabbbf8STobias Grosser 
753*aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
754*aaabbbf8STobias Grosser 
755*aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
756*aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
757*aaabbbf8STobias Grosser 
758*aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
759*aaabbbf8STobias Grosser     isl_set_free(Min);
760*aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
761*aaabbbf8STobias Grosser     isl_ast_build_free(Build);
762*aaabbbf8STobias Grosser     return nullptr;
763*aaabbbf8STobias Grosser   }
764*aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
765*aaabbbf8STobias Grosser 
766*aaabbbf8STobias Grosser   isl_ast_expr *Result =
767*aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
768*aaabbbf8STobias Grosser 
769*aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
770*aaabbbf8STobias Grosser     if (i > 0) {
771*aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
772*aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
773*aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
774*aaabbbf8STobias Grosser     }
775*aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
776*aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
777*aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
778*aaabbbf8STobias Grosser   }
779*aaabbbf8STobias Grosser 
780*aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
781*aaabbbf8STobias Grosser   isl_set_free(Min);
782*aaabbbf8STobias Grosser   isl_ast_build_free(Build);
783*aaabbbf8STobias Grosser 
784*aaabbbf8STobias Grosser   return ResultValue;
785*aaabbbf8STobias Grosser }
786*aaabbbf8STobias Grosser 
78713c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
78813c78e4dSTobias Grosser                                         enum DataDirection Direction) {
78913c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
79013c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
79113c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
79213c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
79313c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
79413c78e4dSTobias Grosser 
79513c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
796*aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
79713c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
79813c78e4dSTobias Grosser 
799b06ff457STobias Grosser   Value *HostPtr;
800b06ff457STobias Grosser 
801b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
802b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
803b06ff457STobias Grosser   else
804b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
80513c78e4dSTobias Grosser 
806*aaabbbf8STobias Grosser   if (Offset) {
807*aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
808*aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
809*aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
810*aaabbbf8STobias Grosser   }
811*aaabbbf8STobias Grosser 
81213c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
81313c78e4dSTobias Grosser 
814*aaabbbf8STobias Grosser   if (Offset) {
815*aaabbbf8STobias Grosser     Size = Builder.CreateSub(
816*aaabbbf8STobias Grosser         Size, Builder.CreateMul(
817*aaabbbf8STobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
818*aaabbbf8STobias Grosser   }
819*aaabbbf8STobias Grosser 
82013c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
82113c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
82213c78e4dSTobias Grosser   else
82313c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
82413c78e4dSTobias Grosser 
82513c78e4dSTobias Grosser   isl_id_free(Id);
82613c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
82713c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
82813c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
82913c78e4dSTobias Grosser }
83013c78e4dSTobias Grosser 
8311fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
83232837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
83332837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
83432837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
83532837fe3STobias Grosser   isl_id_free(Id);
83632837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
83732837fe3STobias Grosser 
83832837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
83932837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
84032837fe3STobias Grosser     createKernel(UserStmt);
84132837fe3STobias Grosser     isl_ast_expr_free(Expr);
84232837fe3STobias Grosser     return;
84332837fe3STobias Grosser   }
84432837fe3STobias Grosser 
84513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
84613c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
84732837fe3STobias Grosser     isl_ast_expr_free(Expr);
84813c78e4dSTobias Grosser     return;
84913c78e4dSTobias Grosser   }
85013c78e4dSTobias Grosser 
85113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
85213c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
85313c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
85438fc0aedSTobias Grosser     return;
85538fc0aedSTobias Grosser   }
85638fc0aedSTobias Grosser 
8575260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
8585260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
8595260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
8605260c041STobias Grosser   isl_id_free(Anno);
8615260c041STobias Grosser 
8625260c041STobias Grosser   switch (KernelStmt->type) {
8635260c041STobias Grosser   case ppcg_kernel_domain:
864edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
8655260c041STobias Grosser     isl_ast_node_free(UserStmt);
8665260c041STobias Grosser     return;
8675260c041STobias Grosser   case ppcg_kernel_copy:
868b513b491STobias Grosser     createKernelCopy(KernelStmt);
8695260c041STobias Grosser     isl_ast_expr_free(Expr);
8705260c041STobias Grosser     isl_ast_node_free(UserStmt);
8715260c041STobias Grosser     return;
8725260c041STobias Grosser   case ppcg_kernel_sync:
8735260c041STobias Grosser     createKernelSync();
8745260c041STobias Grosser     isl_ast_expr_free(Expr);
8755260c041STobias Grosser     isl_ast_node_free(UserStmt);
8765260c041STobias Grosser     return;
8775260c041STobias Grosser   }
8785260c041STobias Grosser 
8795260c041STobias Grosser   isl_ast_expr_free(Expr);
8805260c041STobias Grosser   isl_ast_node_free(UserStmt);
8815260c041STobias Grosser   return;
8825260c041STobias Grosser }
883b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
884b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
885b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
886b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
887b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
888b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
889b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
890b513b491STobias Grosser 
891b513b491STobias Grosser   if (KernelStmt->u.c.read) {
892b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
893b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
894b513b491STobias Grosser   } else {
895b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
896b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
897b513b491STobias Grosser   }
898b513b491STobias Grosser }
8995260c041STobias Grosser 
900edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
901edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
902edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
903edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
904edb885cbSTobias Grosser 
905edb885cbSTobias Grosser   LoopToScevMapT LTS;
906edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
907edb885cbSTobias Grosser 
908edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
909edb885cbSTobias Grosser 
910edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
911edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
912edb885cbSTobias Grosser   else
913a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
914edb885cbSTobias Grosser }
915edb885cbSTobias Grosser 
9165260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
9175260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9185260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
9195260c041STobias Grosser   Builder.CreateCall(Sync, {});
9205260c041STobias Grosser }
9215260c041STobias Grosser 
922edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
923edb885cbSTobias Grosser ///
924edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
925edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
926edb885cbSTobias Grosser ///
927edb885cbSTobias Grosser /// @param Node The node to collect references for.
928edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
929edb885cbSTobias Grosser ///
930edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
931edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
932edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
933edb885cbSTobias Grosser     return isl_bool_true;
934edb885cbSTobias Grosser 
935edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
936edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
937edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
938edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
939edb885cbSTobias Grosser   isl_id_free(Id);
940edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
941edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
942edb885cbSTobias Grosser 
943edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
944edb885cbSTobias Grosser     return isl_bool_true;
945edb885cbSTobias Grosser 
946edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
947edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
948edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
949edb885cbSTobias Grosser   isl_id_free(Id);
950edb885cbSTobias Grosser 
95100bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
952edb885cbSTobias Grosser 
953edb885cbSTobias Grosser   return isl_bool_true;
954edb885cbSTobias Grosser }
955edb885cbSTobias Grosser 
956edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
957edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
958edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
959edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
960edb885cbSTobias Grosser   SubtreeReferences References = {
961edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
962edb885cbSTobias Grosser 
963edb885cbSTobias Grosser   for (const auto &I : IDToValue)
964edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
965edb885cbSTobias Grosser 
966edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
967edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
968edb885cbSTobias Grosser 
969edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
970edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
971edb885cbSTobias Grosser 
972edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
973d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
974edb885cbSTobias Grosser 
975edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
976edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
977edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
978edb885cbSTobias Grosser     assert(IDToValue.count(Id));
979edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
980edb885cbSTobias Grosser     SubtreeValues.remove(Val);
981edb885cbSTobias Grosser     isl_id_free(Id);
982edb885cbSTobias Grosser   }
983edb885cbSTobias Grosser   isl_space_free(Space);
984edb885cbSTobias Grosser 
985edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
986edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
987edb885cbSTobias Grosser     assert(IDToValue.count(Id));
988edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
989edb885cbSTobias Grosser     SubtreeValues.remove(Val);
990edb885cbSTobias Grosser     isl_id_free(Id);
991edb885cbSTobias Grosser   }
992edb885cbSTobias Grosser 
993edb885cbSTobias Grosser   return SubtreeValues;
994edb885cbSTobias Grosser }
995edb885cbSTobias Grosser 
99674dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
99774dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
99874dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
99974dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
100074dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
100174dc3cb4STobias Grosser 
100274dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
100374dc3cb4STobias Grosser     DT.eraseNode(BB);
100474dc3cb4STobias Grosser }
100574dc3cb4STobias Grosser 
100674dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
100774dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
100874dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
100974dc3cb4STobias Grosser     if (L)
101074dc3cb4STobias Grosser       SE.forgetLoop(L);
101174dc3cb4STobias Grosser   }
101274dc3cb4STobias Grosser }
101374dc3cb4STobias Grosser 
101474dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
101574dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
101674dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
101774dc3cb4STobias Grosser     if (L)
101874dc3cb4STobias Grosser       SE.forgetLoop(L);
101974dc3cb4STobias Grosser     LI.removeBlock(&BB);
102074dc3cb4STobias Grosser   }
102174dc3cb4STobias Grosser }
102274dc3cb4STobias Grosser 
102379a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
102479a947c2STobias Grosser   std::vector<Value *> Sizes;
102579a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
102679a947c2STobias Grosser 
102779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
102879a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
102979a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
103079a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
103179a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
103279a947c2STobias Grosser     Sizes.push_back(Res);
103379a947c2STobias Grosser   }
103479a947c2STobias Grosser   isl_ast_build_free(Context);
103579a947c2STobias Grosser 
103679a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
103779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
103879a947c2STobias Grosser 
103979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
104079a947c2STobias Grosser }
104179a947c2STobias Grosser 
104279a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
104379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
104479a947c2STobias Grosser   std::vector<Value *> Sizes;
104579a947c2STobias Grosser 
104679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
104779a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
104879a947c2STobias Grosser     Sizes.push_back(Res);
104979a947c2STobias Grosser   }
105079a947c2STobias Grosser 
105179a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
105279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
105379a947c2STobias Grosser 
105479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
105579a947c2STobias Grosser }
105679a947c2STobias Grosser 
105757693272STobias Grosser Value *
105857693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
105957693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
10604e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
10614e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
106279a947c2STobias Grosser 
106379a947c2STobias Grosser   BasicBlock *EntryBlock =
106479a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
106579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
106679a947c2STobias Grosser   Instruction *Parameters =
106779a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
106879a947c2STobias Grosser 
106979a947c2STobias Grosser   int Index = 0;
107079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
107179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
107279a947c2STobias Grosser       continue;
107379a947c2STobias Grosser 
107479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
107579a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
107679a947c2STobias Grosser 
10770a893f7dSTobias Grosser     Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
107879a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
1079*aaabbbf8STobias Grosser 
1080*aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1081*aaabbbf8STobias Grosser 
1082*aaabbbf8STobias Grosser     if (Offset) {
1083*aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1084*aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1085*aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1086*aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1087*aaabbbf8STobias Grosser     }
1088*aaabbbf8STobias Grosser 
108979a947c2STobias Grosser     Instruction *Param = new AllocaInst(
109079a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
109179a947c2STobias Grosser         EntryBlock->getTerminator());
109279a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
109344143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
109444143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
109579a947c2STobias Grosser     Value *ParamTyped =
109679a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
109779a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
109879a947c2STobias Grosser     Index++;
109979a947c2STobias Grosser   }
110079a947c2STobias Grosser 
1101a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1102a490147cSTobias Grosser 
1103a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1104a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1105a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1106a490147cSTobias Grosser     isl_id_free(Id);
1107a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
1108a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1109a490147cSTobias Grosser         EntryBlock->getTerminator());
1110a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1111a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
1112a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1113a490147cSTobias Grosser     Value *ParamTyped =
1114a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1115a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1116a490147cSTobias Grosser     Index++;
1117a490147cSTobias Grosser   }
1118a490147cSTobias Grosser 
1119d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1120d8b94bcaSTobias Grosser 
1121d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1122d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1123d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1124d8b94bcaSTobias Grosser     isl_id_free(Id);
1125d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
1126d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
1127d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
1128d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1129d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
1130d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1131d8b94bcaSTobias Grosser     Value *ParamTyped =
1132d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1133d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
1134d8b94bcaSTobias Grosser     Index++;
1135d8b94bcaSTobias Grosser   }
1136d8b94bcaSTobias Grosser 
113757693272STobias Grosser   for (auto Val : SubtreeValues) {
113857693272STobias Grosser     Instruction *Param = new AllocaInst(
113957693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
114057693272STobias Grosser         EntryBlock->getTerminator());
114157693272STobias Grosser     Builder.CreateStore(Val, Param);
114257693272STobias Grosser     Value *Slot = Builder.CreateGEP(
114357693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
114457693272STobias Grosser     Value *ParamTyped =
114557693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
114657693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
114757693272STobias Grosser     Index++;
114857693272STobias Grosser   }
114957693272STobias Grosser 
115079a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
115179a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
115279a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
115379a947c2STobias Grosser }
115479a947c2STobias Grosser 
115532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
115632837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
115732837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
115832837fe3STobias Grosser   isl_id_free(Id);
115932837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
116032837fe3STobias Grosser 
1161c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1162c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1163c1c6a2a6STobias Grosser 
1164edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1165edb885cbSTobias Grosser 
116632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
116732837fe3STobias Grosser 
116832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1169472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1170edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1171b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostScalarMap = ScalarMap;
1172b06ff457STobias Grosser   BlockGenerator::ScalarAllocaMapTy HostPHIOpMap = PHIOpMap;
1173b06ff457STobias Grosser   ScalarMap.clear();
1174b06ff457STobias Grosser   PHIOpMap.clear();
117532837fe3STobias Grosser 
1176edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1177edb885cbSTobias Grosser 
1178edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1179edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1180edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1181edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1182edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1183edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1184edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1185edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1186edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1187edb885cbSTobias Grosser     SubtreeValues.insert(V);
1188edb885cbSTobias Grosser   }
1189edb885cbSTobias Grosser 
1190edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
119132837fe3STobias Grosser 
119259ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
119359ab0705STobias Grosser 
119474dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1195c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
119674dc3cb4STobias Grosser   clearDominators(F);
119774dc3cb4STobias Grosser   clearScalarEvolution(F);
119874dc3cb4STobias Grosser   clearLoops(F);
119974dc3cb4STobias Grosser 
120032837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1201472f9654STobias Grosser   IDToValue = HostIDs;
120232837fe3STobias Grosser 
1203b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1204b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1205b06ff457STobias Grosser   PHIOpMap = std::move(HostPHIOpMap);
1206edb885cbSTobias Grosser   EscapeMap.clear();
1207edb885cbSTobias Grosser   IDToSAI.clear();
120874dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
120974dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
121074dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
121174dc3cb4STobias Grosser   LocalArrays.clear();
1212edb885cbSTobias Grosser 
121357693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
121479a947c2STobias Grosser 
121557793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
121657793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
121757793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
121857793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
121957793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
122079a947c2STobias Grosser 
122179a947c2STobias Grosser   Value *GridDimX, *GridDimY;
122279a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
122379a947c2STobias Grosser 
122479a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
122579a947c2STobias Grosser                          BlockDimZ, Parameters);
122657793596STobias Grosser   createCallFreeKernel(GPUKernel);
1227b513b491STobias Grosser 
1228b513b491STobias Grosser   for (auto Id : KernelIds)
1229b513b491STobias Grosser     isl_id_free(Id);
1230b513b491STobias Grosser 
1231b513b491STobias Grosser   KernelIds.clear();
123232837fe3STobias Grosser }
123332837fe3STobias Grosser 
123432837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
123532837fe3STobias Grosser ///
123632837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
123732837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
123832837fe3STobias Grosser   std::string Ret = "e";
123932837fe3STobias Grosser 
124032837fe3STobias Grosser   if (!is64Bit)
124132837fe3STobias Grosser     Ret += "-p:32:32";
124232837fe3STobias Grosser 
124332837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
124432837fe3STobias Grosser 
124532837fe3STobias Grosser   return Ret;
124632837fe3STobias Grosser }
124732837fe3STobias Grosser 
1248edb885cbSTobias Grosser Function *
1249edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1250edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
125132837fe3STobias Grosser   std::vector<Type *> Args;
125232837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
125332837fe3STobias Grosser 
125432837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
125532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
125632837fe3STobias Grosser       continue;
125732837fe3STobias Grosser 
125832837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
125932837fe3STobias Grosser   }
126032837fe3STobias Grosser 
1261f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1262f6044bd0STobias Grosser 
1263f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1264f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1265f6044bd0STobias Grosser 
1266c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1267c84a1995STobias Grosser 
1268cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1269cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1270cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1271cf66ef26STobias Grosser     isl_id_free(Id);
1272cf66ef26STobias Grosser     Args.push_back(Val->getType());
1273cf66ef26STobias Grosser   }
1274c84a1995STobias Grosser 
1275edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1276edb885cbSTobias Grosser     Args.push_back(V->getType());
1277edb885cbSTobias Grosser 
127832837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
127932837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
128032837fe3STobias Grosser                               GPUModule.get());
128132837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
128232837fe3STobias Grosser 
128332837fe3STobias Grosser   auto Arg = FN->arg_begin();
128432837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
128532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
128632837fe3STobias Grosser       continue;
128732837fe3STobias Grosser 
1288edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1289edb885cbSTobias Grosser 
1290edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1291edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1292edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1293edb885cbSTobias Grosser     Value *Val = &*Arg;
1294edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1295edb885cbSTobias Grosser     isl_ast_build *Build =
1296edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1297f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1298edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1299edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1300edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1301edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1302edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1303edb885cbSTobias Grosser     }
1304edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1305edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
130674dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1307edb885cbSTobias Grosser 
1308edb885cbSTobias Grosser     isl_ast_build_free(Build);
1309b513b491STobias Grosser     KernelIds.push_back(Id);
1310edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
131132837fe3STobias Grosser     Arg++;
131232837fe3STobias Grosser   }
131332837fe3STobias Grosser 
1314f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1315f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1316f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1317f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1318f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1319f6044bd0STobias Grosser     Arg++;
1320f6044bd0STobias Grosser   }
1321f6044bd0STobias Grosser 
1322c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1323c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1324c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
132512453403STobias Grosser     Value *Val = IDToValue[Id];
132612453403STobias Grosser     ValueMap[Val] = &*Arg;
1327c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1328c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1329c84a1995STobias Grosser     Arg++;
1330c84a1995STobias Grosser   }
1331c84a1995STobias Grosser 
1332edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1333edb885cbSTobias Grosser     Arg->setName(V->getName());
1334edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1335edb885cbSTobias Grosser     Arg++;
1336edb885cbSTobias Grosser   }
1337edb885cbSTobias Grosser 
133832837fe3STobias Grosser   return FN;
133932837fe3STobias Grosser }
134032837fe3STobias Grosser 
1341472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1342472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1343472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1344472f9654STobias Grosser 
1345472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1346472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1347472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1348472f9654STobias Grosser 
1349472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1350472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1351472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1352472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1353472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1354472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1355472f9654STobias Grosser     IDToValue[Id] = Val;
1356472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1357472f9654STobias Grosser   };
1358472f9654STobias Grosser 
1359472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1360472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1361472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1362472f9654STobias Grosser   }
1363472f9654STobias Grosser 
1364472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1365472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1366472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1367472f9654STobias Grosser   }
1368472f9654STobias Grosser }
1369472f9654STobias Grosser 
137000bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
137100bb5a99STobias Grosser   auto Arg = FN->arg_begin();
137200bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
137300bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
137400bb5a99STobias Grosser       continue;
137500bb5a99STobias Grosser 
137600bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
137700bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
137800bb5a99STobias Grosser     isl_id_free(Id);
137900bb5a99STobias Grosser 
138000bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
138100bb5a99STobias Grosser       Arg++;
138200bb5a99STobias Grosser       continue;
138300bb5a99STobias Grosser     }
138400bb5a99STobias Grosser 
1385b06ff457STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
138600bb5a99STobias Grosser     Value *ArgPtr = &*Arg;
138700bb5a99STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
138800bb5a99STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
138900bb5a99STobias Grosser     Value *Val = Builder.CreateLoad(TypedArgPtr);
139000bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
139100bb5a99STobias Grosser 
139200bb5a99STobias Grosser     Arg++;
139300bb5a99STobias Grosser   }
139400bb5a99STobias Grosser }
139500bb5a99STobias Grosser 
1396b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1397b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1398b513b491STobias Grosser 
1399b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1400b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1401b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1402b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1403b513b491STobias Grosser 
1404f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1405b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1406b513b491STobias Grosser 
1407f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1408928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1409b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1410f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1411b513b491STobias Grosser       isl_val_free(Val);
1412b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1413928d7573STobias Grosser     }
1414928d7573STobias Grosser 
1415928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1416928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1417928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1418928d7573STobias Grosser       isl_val_free(Val);
1419b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1420b513b491STobias Grosser     }
1421b513b491STobias Grosser 
1422130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1423130ca30fSTobias Grosser     Value *Allocation;
1424130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1425130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1426130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1427130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1428130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1429f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1430f919d8b3STobias Grosser 
1431130ca30fSTobias Grosser       Allocation = GlobalVar;
1432130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1433130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1434130ca30fSTobias Grosser     } else {
1435130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1436130ca30fSTobias Grosser     }
1437130ca30fSTobias Grosser     SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes,
1438130ca30fSTobias Grosser                                      ScopArrayInfo::MK_Array);
1439b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1440130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1441130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1442b513b491STobias Grosser     KernelIds.push_back(Id);
1443b513b491STobias Grosser     IDToSAI[Id] = SAI;
1444b513b491STobias Grosser   }
1445b513b491STobias Grosser }
1446b513b491STobias Grosser 
1447edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1448edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
144932837fe3STobias Grosser 
145032837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
145132837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
145232837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
145332837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
145432837fe3STobias Grosser 
1455edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
145632837fe3STobias Grosser 
145759ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
145832837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
145932837fe3STobias Grosser 
146059ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
146159ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
146259ab0705STobias Grosser 
146332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
146432837fe3STobias Grosser   Builder.CreateRetVoid();
146532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1466472f9654STobias Grosser 
1467629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1468629109b6STobias Grosser 
146900bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1470b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1471472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
147232837fe3STobias Grosser }
147332837fe3STobias Grosser 
147474dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
147574dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
147674dc3cb4STobias Grosser   std::string ErrMsg;
147774dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
147874dc3cb4STobias Grosser 
147974dc3cb4STobias Grosser   if (!GPUTarget) {
148074dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
148174dc3cb4STobias Grosser     return "";
148274dc3cb4STobias Grosser   }
148374dc3cb4STobias Grosser 
148474dc3cb4STobias Grosser   TargetOptions Options;
148574dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
148674dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
148774dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
148874dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
148974dc3cb4STobias Grosser 
149074dc3cb4STobias Grosser   SmallString<0> ASMString;
149174dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
149274dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
149374dc3cb4STobias Grosser 
149474dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
149574dc3cb4STobias Grosser 
149674dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
149774dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
149874dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
149974dc3cb4STobias Grosser     return "";
150074dc3cb4STobias Grosser   }
150174dc3cb4STobias Grosser 
150274dc3cb4STobias Grosser   PM.run(*GPUModule);
150374dc3cb4STobias Grosser 
150474dc3cb4STobias Grosser   return ASMStream.str();
150574dc3cb4STobias Grosser }
150674dc3cb4STobias Grosser 
150757793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
15085857b701STobias Grosser   if (verifyModule(*GPUModule)) {
15095857b701STobias Grosser     BuildSuccessful = false;
15105857b701STobias Grosser     return "";
15115857b701STobias Grosser   }
151232837fe3STobias Grosser 
151332837fe3STobias Grosser   if (DumpKernelIR)
151432837fe3STobias Grosser     outs() << *GPUModule << "\n";
151532837fe3STobias Grosser 
15169a18d559STobias Grosser   // Optimize module.
15179a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
15189a18d559STobias Grosser   PassManagerBuilder PassBuilder;
15199a18d559STobias Grosser   PassBuilder.OptLevel = 3;
15209a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
15219a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
15229a18d559STobias Grosser   OptPasses.run(*GPUModule);
15239a18d559STobias Grosser 
152474dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
152574dc3cb4STobias Grosser 
152674dc3cb4STobias Grosser   if (DumpKernelASM)
152774dc3cb4STobias Grosser     outs() << Assembly << "\n";
152874dc3cb4STobias Grosser 
152932837fe3STobias Grosser   GPUModule.release();
1530472f9654STobias Grosser   KernelIDs.clear();
153157793596STobias Grosser 
153257793596STobias Grosser   return Assembly;
153332837fe3STobias Grosser }
153432837fe3STobias Grosser 
15359dfe4e7cSTobias Grosser namespace {
15369dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
15379dfe4e7cSTobias Grosser public:
15389dfe4e7cSTobias Grosser   static char ID;
15399dfe4e7cSTobias Grosser 
1540e938517eSTobias Grosser   /// The scop that is currently processed.
1541e938517eSTobias Grosser   Scop *S;
1542e938517eSTobias Grosser 
154338fc0aedSTobias Grosser   LoopInfo *LI;
154438fc0aedSTobias Grosser   DominatorTree *DT;
154538fc0aedSTobias Grosser   ScalarEvolution *SE;
154638fc0aedSTobias Grosser   const DataLayout *DL;
154738fc0aedSTobias Grosser   RegionInfo *RI;
154838fc0aedSTobias Grosser 
15499dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
15509dfe4e7cSTobias Grosser 
1551e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1552e938517eSTobias Grosser   ///
1553e938517eSTobias Grosser   /// @returns The compilation options.
1554e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1555e938517eSTobias Grosser     auto DebugOptions =
1556e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1557e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1558e938517eSTobias Grosser 
1559e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1560e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1561e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1562e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
15638950ceadSTobias Grosser     DebugOptions->verbose = false;
1564e938517eSTobias Grosser 
1565e938517eSTobias Grosser     Options->debug = DebugOptions;
1566e938517eSTobias Grosser 
1567e938517eSTobias Grosser     Options->reschedule = true;
1568e938517eSTobias Grosser     Options->scale_tile_loops = false;
1569e938517eSTobias Grosser     Options->wrap = false;
1570e938517eSTobias Grosser 
1571e938517eSTobias Grosser     Options->non_negative_parameters = false;
1572e938517eSTobias Grosser     Options->ctx = nullptr;
1573e938517eSTobias Grosser     Options->sizes = nullptr;
1574e938517eSTobias Grosser 
15754eaedde5STobias Grosser     Options->tile_size = 32;
15764eaedde5STobias Grosser 
1577130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1578b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1579b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1580e938517eSTobias Grosser 
1581e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1582e938517eSTobias Grosser     Options->openmp = false;
1583e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1584e938517eSTobias Grosser     Options->live_range_reordering = false;
1585e938517eSTobias Grosser 
1586e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1587e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1588e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1589e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1590e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1591e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1592e938517eSTobias Grosser 
1593e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1594e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1595e938517eSTobias Grosser 
1596e938517eSTobias Grosser     return Options;
1597e938517eSTobias Grosser   }
1598e938517eSTobias Grosser 
1599f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1600f384594dSTobias Grosser   ///
1601f384594dSTobias Grosser   /// Instead of a normal access of the form:
1602f384594dSTobias Grosser   ///
1603f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1604f384594dSTobias Grosser   ///
1605f384594dSTobias Grosser   /// a tagged access has the form
1606f384594dSTobias Grosser   ///
1607f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1608f384594dSTobias Grosser   ///
1609f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1610f384594dSTobias Grosser   /// triggered the access.
1611f384594dSTobias Grosser   ///
1612f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1613f384594dSTobias Grosser   ///
1614f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1615f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1616f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1617f384594dSTobias Grosser 
1618f384594dSTobias Grosser     for (auto &Stmt : *S)
1619f384594dSTobias Grosser       for (auto &Acc : Stmt)
1620f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1621f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1622f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1623f384594dSTobias Grosser 
1624f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1625f384594dSTobias Grosser           Space = isl_space_range(Space);
1626f384594dSTobias Grosser           Space = isl_space_from_range(Space);
16276293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1628f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1629f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1630f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1631f384594dSTobias Grosser         }
1632f384594dSTobias Grosser 
1633f384594dSTobias Grosser     return Accesses;
1634f384594dSTobias Grosser   }
1635f384594dSTobias Grosser 
1636f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1637f384594dSTobias Grosser   ///
1638f384594dSTobias Grosser   /// @see getTaggedAccesses
1639f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1640f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1641f384594dSTobias Grosser   }
1642f384594dSTobias Grosser 
1643f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1644f384594dSTobias Grosser   ///
1645f384594dSTobias Grosser   /// @see getTaggedAccesses
1646f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1647f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1648f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1649f384594dSTobias Grosser   }
1650f384594dSTobias Grosser 
1651f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1652f384594dSTobias Grosser   ///
1653f384594dSTobias Grosser   /// @see getTaggedAccesses
1654f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1655f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1656f384594dSTobias Grosser   }
1657f384594dSTobias Grosser 
1658aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1659aef5196fSTobias Grosser   ///
1660aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1661aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1662aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1663aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1664aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1665aef5196fSTobias Grosser   /// the data format that ppcg expects.
1666aef5196fSTobias Grosser   ///
1667aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1668aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1669aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1670bd81a7eeSTobias Grosser         S->getIslCtx(),
1671bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1672aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1673aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1674aef5196fSTobias Grosser 
1675aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1676aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1677aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1678aef5196fSTobias Grosser     }
1679aef5196fSTobias Grosser 
1680aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1681d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1682aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1683aef5196fSTobias Grosser     }
1684aef5196fSTobias Grosser 
1685aef5196fSTobias Grosser     isl_space_free(Space);
1686aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1687aef5196fSTobias Grosser 
1688aef5196fSTobias Grosser     return Names;
1689aef5196fSTobias Grosser   }
1690aef5196fSTobias Grosser 
1691e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1692e938517eSTobias Grosser   ///
1693f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1694f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1695f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1696f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1697e938517eSTobias Grosser   ///
1698e938517eSTobias Grosser   /// @returns A new ppcg scop.
1699e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1700e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1701e938517eSTobias Grosser 
1702e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1703e938517eSTobias Grosser 
1704e938517eSTobias Grosser     PPCGScop->start = 0;
1705e938517eSTobias Grosser     PPCGScop->end = 0;
1706e938517eSTobias Grosser 
1707f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1708f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1709e938517eSTobias Grosser     PPCGScop->call = nullptr;
1710f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1711f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1712e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1713f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1714f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1715f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1716f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1717e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1718f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1719e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1720e938517eSTobias Grosser 
1721e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1722e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1723e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1724e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1725e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1726e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1727e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1728e938517eSTobias Grosser 
1729f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1730aef5196fSTobias Grosser     PPCGScop->names = getNames();
1731e938517eSTobias Grosser 
1732e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1733e938517eSTobias Grosser 
1734f384594dSTobias Grosser     compute_tagger(PPCGScop);
1735f384594dSTobias Grosser     compute_dependences(PPCGScop);
1736f384594dSTobias Grosser 
1737e938517eSTobias Grosser     return PPCGScop;
1738e938517eSTobias Grosser   }
1739e938517eSTobias Grosser 
174060f63b49STobias Grosser   /// Collect the array acesses in a statement.
174160f63b49STobias Grosser   ///
174260f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
174360f63b49STobias Grosser   ///
174460f63b49STobias Grosser   /// @returns A list of array accesses.
174560f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
174660f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
174760f63b49STobias Grosser 
174860f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
174960f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
175060f63b49STobias Grosser       Access->read = Acc->isRead();
175160f63b49STobias Grosser       Access->write = Acc->isWrite();
175260f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
175360f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
175460f63b49STobias Grosser       Space = isl_space_range(Space);
175560f63b49STobias Grosser       Space = isl_space_from_range(Space);
17566293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
175760f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
175860f63b49STobias Grosser       Access->tagged_access =
175960f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1760b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
176160f63b49STobias Grosser       Access->ref_id = Acc->getId();
176260f63b49STobias Grosser       Access->next = Accesses;
1763b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
176460f63b49STobias Grosser       Accesses = Access;
176560f63b49STobias Grosser     }
176660f63b49STobias Grosser 
176760f63b49STobias Grosser     return Accesses;
176860f63b49STobias Grosser   }
176960f63b49STobias Grosser 
177069b46751STobias Grosser   /// Collect the list of GPU statements.
177169b46751STobias Grosser   ///
177269b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
177369b46751STobias Grosser   /// as well as a list with all memory accesses.
177469b46751STobias Grosser   ///
177569b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
177669b46751STobias Grosser   ///
177769b46751STobias Grosser   /// @returns A linked-list of statements.
177869b46751STobias Grosser   gpu_stmt *getStatements() {
177969b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
178069b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
178169b46751STobias Grosser 
178269b46751STobias Grosser     int i = 0;
178369b46751STobias Grosser     for (auto &Stmt : *S) {
178469b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
178569b46751STobias Grosser 
178669b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
178769b46751STobias Grosser 
178869b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
178969b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
179060f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
179169b46751STobias Grosser       i++;
179269b46751STobias Grosser     }
179369b46751STobias Grosser 
179469b46751STobias Grosser     return Stmts;
179569b46751STobias Grosser   }
179669b46751STobias Grosser 
179760f63b49STobias Grosser   /// Derive the extent of an array.
179860f63b49STobias Grosser   ///
1799d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
1800d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
1801d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
1802d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
1803d58acf86STobias Grosser   /// subscript value for the first dimension.
180460f63b49STobias Grosser   ///
180560f63b49STobias Grosser   /// @param Array The array to derive the extent for.
180660f63b49STobias Grosser   ///
180760f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
180860f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
1809d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
181060f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
181160f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
1812d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
181360f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
1814d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1815d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
1816d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
1817d58acf86STobias Grosser 
1818d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
1819d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1820d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
1821d58acf86STobias Grosser     }
1822d58acf86STobias Grosser 
1823d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
1824d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
1825d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
1826d58acf86STobias Grosser     }
1827d58acf86STobias Grosser 
182860f63b49STobias Grosser     isl_set *AccessSet =
182960f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
183060f63b49STobias Grosser 
1831d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
1832d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
1833d58acf86STobias Grosser 
1834d58acf86STobias Grosser     isl_pw_aff *Val =
1835d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
1836d58acf86STobias Grosser 
1837d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
1838d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
1839d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
1840d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1841d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
1842d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
1843d58acf86STobias Grosser     OuterMin =
1844d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
1845d58acf86STobias Grosser     OuterMax =
1846d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
1847d58acf86STobias Grosser 
1848d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
1849d58acf86STobias Grosser 
1850d58acf86STobias Grosser     Extent = isl_set_intersect(
1851d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
1852d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
1853d58acf86STobias Grosser 
1854d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
1855d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
1856d58acf86STobias Grosser 
1857d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i) {
1858d58acf86STobias Grosser       isl_pw_aff *PwAff =
1859d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
1860d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
1861d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
1862d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
1863d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
1864d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
1865d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
1866d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
1867d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
1868d58acf86STobias Grosser     }
1869d58acf86STobias Grosser 
1870d58acf86STobias Grosser     return Extent;
187160f63b49STobias Grosser   }
187260f63b49STobias Grosser 
187360f63b49STobias Grosser   /// Derive the bounds of an array.
187460f63b49STobias Grosser   ///
187560f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
187660f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
187760f63b49STobias Grosser   /// ScopArrayInfo.
187860f63b49STobias Grosser   ///
187960f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
188060f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
188160f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
188260f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
188302293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
188402293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
188502293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
188602293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
188702293ed7STobias Grosser         isl_set_free(Dom);
188802293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
188902293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
189002293ed7STobias Grosser       } else {
189160f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
189260f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
189360f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
189460f63b49STobias Grosser         isl_set_free(Dom);
189560f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
189602293ed7STobias Grosser         isl_local_space *LS =
189702293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
189860f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
189960f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
190060f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
190160f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
190260f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
190360f63b49STobias Grosser       }
190402293ed7STobias Grosser     }
190560f63b49STobias Grosser 
190660f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
190760f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
190860f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
190960f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
191060f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
191160f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
191260f63b49STobias Grosser     }
191360f63b49STobias Grosser   }
191460f63b49STobias Grosser 
191560f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
191660f63b49STobias Grosser   ///
191760f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
191860f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
191960f63b49STobias Grosser     int i = 0;
1920d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
192160f63b49STobias Grosser       std::string TypeName;
192260f63b49STobias Grosser       raw_string_ostream OS(TypeName);
192360f63b49STobias Grosser 
192460f63b49STobias Grosser       OS << *Array->getElementType();
192560f63b49STobias Grosser       TypeName = OS.str();
192660f63b49STobias Grosser 
192760f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
192860f63b49STobias Grosser 
192960f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
193060f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
193160f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
193260f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
193360f63b49STobias Grosser       PPCGArray.extent = nullptr;
193460f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
193560f63b49STobias Grosser       PPCGArray.bound =
193660f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
193760f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
193860f63b49STobias Grosser       PPCGArray.n_ref = 0;
193960f63b49STobias Grosser       PPCGArray.refs = nullptr;
194060f63b49STobias Grosser       PPCGArray.accessed = true;
194160f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
194260f63b49STobias Grosser       PPCGArray.has_compound_element = false;
194360f63b49STobias Grosser       PPCGArray.local = false;
194460f63b49STobias Grosser       PPCGArray.declare_local = false;
194560f63b49STobias Grosser       PPCGArray.global = false;
194660f63b49STobias Grosser       PPCGArray.linearize = false;
194760f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
194813c78e4dSTobias Grosser       PPCGArray.user = Array;
194960f63b49STobias Grosser 
195060f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
19512d010dafSTobias Grosser       i++;
1952b9fc860aSTobias Grosser 
1953b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
195460f63b49STobias Grosser     }
195560f63b49STobias Grosser   }
195660f63b49STobias Grosser 
195760f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
195860f63b49STobias Grosser   ///
195960f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
196060f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
196160f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
196260f63b49STobias Grosser 
1963d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
196460f63b49STobias Grosser       isl_space *Space = Array->getSpace();
196560f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
196660f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
196760f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
196860f63b49STobias Grosser     }
196960f63b49STobias Grosser 
197060f63b49STobias Grosser     return Maps;
197160f63b49STobias Grosser   }
197260f63b49STobias Grosser 
1973e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1974e938517eSTobias Grosser   ///
1975e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1976e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1977e938517eSTobias Grosser 
1978e938517eSTobias Grosser     if (!PPCGScop)
1979e938517eSTobias Grosser       return nullptr;
1980e938517eSTobias Grosser 
1981e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1982e938517eSTobias Grosser 
1983e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1984e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1985aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
198660f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
198760f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
198860f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
198960f63b49STobias Grosser     PPCGProg->tagged_must_kill =
199060f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
199160f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
199260f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
1993e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1994e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
199569b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
199669b46751STobias Grosser     PPCGProg->stmts = getStatements();
199760f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
199860f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
199960f63b49STobias Grosser                                        PPCGProg->n_array);
200060f63b49STobias Grosser 
200160f63b49STobias Grosser     createArrays(PPCGProg);
2002e938517eSTobias Grosser 
2003d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2004d58acf86STobias Grosser 
2005e938517eSTobias Grosser     return PPCGProg;
2006e938517eSTobias Grosser   }
2007e938517eSTobias Grosser 
200869b46751STobias Grosser   struct PrintGPUUserData {
200969b46751STobias Grosser     struct cuda_info *CudaInfo;
201069b46751STobias Grosser     struct gpu_prog *PPCGProg;
201169b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
201269b46751STobias Grosser   };
201369b46751STobias Grosser 
201469b46751STobias Grosser   /// Print a user statement node in the host code.
201569b46751STobias Grosser   ///
201669b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
201769b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
201869b46751STobias Grosser   /// host ast.
201969b46751STobias Grosser   ///
202069b46751STobias Grosser   /// @param P The printer to print to
202169b46751STobias Grosser   /// @param Options The printing options to use
202269b46751STobias Grosser   /// @param Node The node to print
202369b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
202469b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
202569b46751STobias Grosser   ///
202669b46751STobias Grosser   /// @returns A printer to which the output has been printed.
202769b46751STobias Grosser   static __isl_give isl_printer *
202869b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
202969b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
203069b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
203169b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
203269b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
203369b46751STobias Grosser 
203469b46751STobias Grosser     if (Id) {
203520251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
203620251734STobias Grosser 
203720251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
203820251734STobias Grosser       // otherwise try to call pet functionality that is not available in
203920251734STobias Grosser       // Polly.
204020251734STobias Grosser       if (IsUser) {
204120251734STobias Grosser         P = isl_printer_start_line(P);
204220251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
204320251734STobias Grosser         P = isl_printer_end_line(P);
204420251734STobias Grosser         isl_id_free(Id);
204520251734STobias Grosser         isl_ast_print_options_free(Options);
204620251734STobias Grosser         return P;
204720251734STobias Grosser       }
204820251734STobias Grosser 
204969b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
205069b46751STobias Grosser       isl_id_free(Id);
205169b46751STobias Grosser       Data->Kernels.push_back(Kernel);
205269b46751STobias Grosser     }
205369b46751STobias Grosser 
205469b46751STobias Grosser     return print_host_user(P, Options, Node, User);
205569b46751STobias Grosser   }
205669b46751STobias Grosser 
205769b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
205869b46751STobias Grosser   ///
205969b46751STobias Grosser   /// @param Kernel The kernel to print
206069b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
206169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
206269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
206369b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
206469b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
206569b46751STobias Grosser     char *String = isl_printer_get_str(P);
206669b46751STobias Grosser     printf("%s\n", String);
206769b46751STobias Grosser     free(String);
206869b46751STobias Grosser     isl_printer_free(P);
206969b46751STobias Grosser   }
207069b46751STobias Grosser 
207169b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
207269b46751STobias Grosser   ///
207369b46751STobias Grosser   /// @param Tree An AST describing GPU code
207469b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
207569b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
207669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
207769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
207869b46751STobias Grosser 
207969b46751STobias Grosser     PrintGPUUserData Data;
208069b46751STobias Grosser     Data.PPCGProg = PPCGProg;
208169b46751STobias Grosser 
208269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
208369b46751STobias Grosser     Options =
208469b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
208569b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
208669b46751STobias Grosser     char *String = isl_printer_get_str(P);
208769b46751STobias Grosser     printf("# host\n");
208869b46751STobias Grosser     printf("%s\n", String);
208969b46751STobias Grosser     free(String);
209069b46751STobias Grosser     isl_printer_free(P);
209169b46751STobias Grosser 
209269b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
209369b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
209469b46751STobias Grosser       printKernel(Kernel);
209569b46751STobias Grosser     }
209669b46751STobias Grosser   }
209769b46751STobias Grosser 
2098f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2099f384594dSTobias Grosser   //
2100f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2101f384594dSTobias Grosser   //
2102f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2103f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2104f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2105f384594dSTobias Grosser   //
2106f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2107f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2108f384594dSTobias Grosser   // strategy directly from this pass.
2109f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2110f384594dSTobias Grosser 
2111f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2112f384594dSTobias Grosser 
2113f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2114f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2115f384594dSTobias Grosser     PPCGGen->print = nullptr;
2116f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
211760c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2118f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2119f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2120f384594dSTobias Grosser     PPCGGen->types.n = 0;
2121f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2122f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2123f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2124f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2125f384594dSTobias Grosser 
2126f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2127f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2128f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
21292341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2130f384594dSTobias Grosser 
2131f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2132f384594dSTobias Grosser 
2133aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2134aef5196fSTobias Grosser 
213569b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2136aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
213769b46751STobias Grosser     } else {
2138aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
213969b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
214069b46751STobias Grosser     }
2141aef5196fSTobias Grosser 
2142f384594dSTobias Grosser     if (DumpSchedule) {
2143f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2144f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2145f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2146f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2147f384594dSTobias Grosser       if (Schedule)
2148f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2149f384594dSTobias Grosser       else
2150f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2151f384594dSTobias Grosser 
2152f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2153f384594dSTobias Grosser       isl_printer_free(P);
2154f384594dSTobias Grosser     }
2155f384594dSTobias Grosser 
215669b46751STobias Grosser     if (DumpCode) {
215769b46751STobias Grosser       printf("Code\n");
215869b46751STobias Grosser       printf("====\n");
215969b46751STobias Grosser       if (PPCGGen->tree)
216069b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
216169b46751STobias Grosser       else
216269b46751STobias Grosser         printf("No code generated\n");
216369b46751STobias Grosser     }
216469b46751STobias Grosser 
2165f384594dSTobias Grosser     isl_schedule_free(Schedule);
2166f384594dSTobias Grosser 
2167f384594dSTobias Grosser     return PPCGGen;
2168f384594dSTobias Grosser   }
2169f384594dSTobias Grosser 
2170f384594dSTobias Grosser   /// Free gpu_gen structure.
2171f384594dSTobias Grosser   ///
2172f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2173f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2174f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2175f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2176f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2177f384594dSTobias Grosser     free(PPCGGen);
2178f384594dSTobias Grosser   }
2179f384594dSTobias Grosser 
2180b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2181b307ed4dSTobias Grosser   ///
2182b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2183b307ed4dSTobias Grosser   /// ourselves.
2184b307ed4dSTobias Grosser   ///
2185b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2186b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2187b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2188b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2189b307ed4dSTobias Grosser     free(PPCGScop->options);
2190b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2191b307ed4dSTobias Grosser   }
2192b307ed4dSTobias Grosser 
219338fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
219438fc0aedSTobias Grosser   ///
219532837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
219632837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
219732837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
219838fc0aedSTobias Grosser     ScopAnnotator Annotator;
219938fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
220038fc0aedSTobias Grosser 
220138fc0aedSTobias Grosser     Region *R = &S->getRegion();
220238fc0aedSTobias Grosser 
220338fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
220438fc0aedSTobias Grosser 
220538fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
220638fc0aedSTobias Grosser 
220738fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
220838fc0aedSTobias Grosser 
220932837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
221032837fe3STobias Grosser                                Prog);
221138fc0aedSTobias Grosser 
221238fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
221338fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
221438fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
221538fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
221638fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
221738fc0aedSTobias Grosser     // code generating this scop.
221838fc0aedSTobias Grosser     BasicBlock *StartBlock =
221938fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
222038fc0aedSTobias Grosser 
222138fc0aedSTobias Grosser     // TODO: Handle LICM
222238fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
222338fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
222438fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2225cb1aef8dSTobias Grosser 
2226cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
2227cb1aef8dSTobias Grosser     isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build);
2228cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2229cb1aef8dSTobias Grosser 
2230cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2231cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2232cb1aef8dSTobias Grosser 
223338fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2234fa7b0802STobias Grosser 
2235fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
223638fc0aedSTobias Grosser     NodeBuilder.create(Root);
22378ed5e599STobias Grosser     NodeBuilder.finalize();
22385857b701STobias Grosser 
22395857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
22405857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
224138fc0aedSTobias Grosser   }
224238fc0aedSTobias Grosser 
2243e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2244e938517eSTobias Grosser     S = &CurrentScop;
224538fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
224638fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
224738fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
224838fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
224938fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2250e938517eSTobias Grosser 
22512d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
22522d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
22532d58a64eSTobias Grosser       return false;
22542d58a64eSTobias Grosser 
2255e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2256e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2257f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
225838fc0aedSTobias Grosser 
225938fc0aedSTobias Grosser     if (PPCGGen->tree)
226032837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
226138fc0aedSTobias Grosser 
2262b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2263f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2264e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2265e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2266e938517eSTobias Grosser 
2267e938517eSTobias Grosser     return true;
2268e938517eSTobias Grosser   }
22699dfe4e7cSTobias Grosser 
22709dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
22719dfe4e7cSTobias Grosser 
22729dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
22739dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
22749dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
22759dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
22769dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
22779dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
22789dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
22799dfe4e7cSTobias Grosser 
22809dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
22819dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
22829dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
22839dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
22849dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
22859dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
22869dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
22879dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
22889dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
22899dfe4e7cSTobias Grosser 
22909dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
22919dfe4e7cSTobias Grosser     //        region tree.
22929dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
22939dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
22949dfe4e7cSTobias Grosser   }
22959dfe4e7cSTobias Grosser };
22969dfe4e7cSTobias Grosser }
22979dfe4e7cSTobias Grosser 
22989dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
22999dfe4e7cSTobias Grosser 
23009dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
23019dfe4e7cSTobias Grosser 
23029dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
23039dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
23049dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
23059dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
23069dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
23079dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
23089dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
23099dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
23109dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
23119dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2312