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 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
21f384594dSTobias Grosser #include "polly/Options.h"
22629109b6STobias Grosser #include "polly/ScopDetection.h"
239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.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 
90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
91abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
92abed4969SSiddharth Bhat                                             " that all memory has been"
93abed4969SSiddharth Bhat                                             " declared as managed memory"),
94abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
95abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
96abed4969SSiddharth Bhat 
9774dc3cb4STobias Grosser static cl::opt<std::string>
9874dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
9974dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
10074dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
10174dc3cb4STobias Grosser 
10282f2af35STobias Grosser static cl::opt<int>
10382f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
10482f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
10582f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
10682f2af35STobias Grosser 
10760c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
10860c60025STobias Grosser ///
10960c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
11060c60025STobias Grosser /// of the scheduled ScopStmts.
11160c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
112edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
11360c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
11460c60025STobias Grosser                                        isl_id *Id, void *User),
11560c60025STobias Grosser     void *UserIndex,
11660c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
117edb885cbSTobias Grosser     void *UserExpr) {
11860c60025STobias Grosser 
119edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
12060c60025STobias Grosser 
121edb885cbSTobias Grosser   isl_ctx *Ctx;
122edb885cbSTobias Grosser 
123edb885cbSTobias Grosser   if (!Stmt || !Build)
124edb885cbSTobias Grosser     return NULL;
125edb885cbSTobias Grosser 
126edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
127edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
128edb885cbSTobias Grosser 
129edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
130edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
131edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
132edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
133edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
134edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
135edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
136edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
137edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
138edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
139edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
140edb885cbSTobias Grosser   }
141edb885cbSTobias Grosser 
142edb885cbSTobias Grosser   return RefToExpr;
14360c60025STobias Grosser }
144f384594dSTobias Grosser 
145a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
146a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
147a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
148a90be207SSiddharth Bhat   if (bytes == 0)
149a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
150a90be207SSiddharth Bhat   return bytes;
151a90be207SSiddharth Bhat }
152a90be207SSiddharth Bhat 
15338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
15438fc0aedSTobias Grosser ///
15538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
156a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
15738fc0aedSTobias Grosser /// for generating GPU specific user nodes.
15838fc0aedSTobias Grosser ///
15938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
16038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
16138fc0aedSTobias Grosser public:
1622d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
16338fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
164acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
16517f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
1662d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
16717f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
168edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
169edb885cbSTobias Grosser   }
17038fc0aedSTobias Grosser 
171fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
172fa7b0802STobias Grosser   void initializeAfterRTH();
173fa7b0802STobias Grosser 
174fa7b0802STobias Grosser   /// Finalize the generated scop.
175fa7b0802STobias Grosser   virtual void finalize();
176fa7b0802STobias Grosser 
1775857b701STobias Grosser   /// Track if the full build process was successful.
1785857b701STobias Grosser   ///
1795857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
1805857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
1815857b701STobias Grosser   bool BuildSuccessful = true;
1825857b701STobias Grosser 
183bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
184bc653f20STobias Grosser   unsigned DeepestSequential = 0;
185bc653f20STobias Grosser 
186bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
187bc653f20STobias Grosser   unsigned DeepestParallel = 0;
188bc653f20STobias Grosser 
18938fc0aedSTobias Grosser private:
19074dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
19174dc3cb4STobias Grosser   ///
19274dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
19374dc3cb4STobias Grosser   /// more.
19474dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
19574dc3cb4STobias Grosser 
19613c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
19713c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1987287aeddSTobias Grosser 
199fa7b0802STobias Grosser   /// The current GPU context.
200fa7b0802STobias Grosser   Value *GPUContext;
201fa7b0802STobias Grosser 
202b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
203b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
204b513b491STobias Grosser 
20532837fe3STobias Grosser   /// A module containing GPU code.
20632837fe3STobias Grosser   ///
20732837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
20832837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
20932837fe3STobias Grosser 
21032837fe3STobias Grosser   /// The GPU program we generate code for.
21132837fe3STobias Grosser   gpu_prog *Prog;
21232837fe3STobias Grosser 
21317f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
21417f01968SSiddharth Bhat   GPURuntime Runtime;
21517f01968SSiddharth Bhat 
21617f01968SSiddharth Bhat   /// The GPU Architecture to target.
21717f01968SSiddharth Bhat   GPUArch Arch;
21817f01968SSiddharth Bhat 
219472f9654STobias Grosser   /// Class to free isl_ids.
220472f9654STobias Grosser   class IslIdDeleter {
221472f9654STobias Grosser   public:
222472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
223472f9654STobias Grosser   };
224472f9654STobias Grosser 
225472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
226472f9654STobias Grosser   ///
227472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
228472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
229472f9654STobias Grosser 
230edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
231edb885cbSTobias Grosser 
23238fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
23338fc0aedSTobias Grosser   ///
23438fc0aedSTobias Grosser   /// These AST nodes can be of type:
23538fc0aedSTobias Grosser   ///
23638fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
23738fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
23813c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
2395260c041STobias Grosser   ///   - In-kernel synchronization
2405260c041STobias Grosser   ///   - In-kernel memory copy statement
24138fc0aedSTobias Grosser   ///
2421fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
2431fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
24432837fe3STobias Grosser 
24513c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
24613c78e4dSTobias Grosser 
24713c78e4dSTobias Grosser   /// Create code for a data transfer statement
24813c78e4dSTobias Grosser   ///
24913c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
25013c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
25113c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
25213c78e4dSTobias Grosser                           enum DataDirection Direction);
25313c78e4dSTobias Grosser 
254edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
255edb885cbSTobias Grosser   ///
256edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
257edb885cbSTobias Grosser   ///
258*f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
259*f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
260*f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
261*f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
262*f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
263*f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
264edb885cbSTobias Grosser 
26579a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
26679a947c2STobias Grosser   ///
26779a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
26879a947c2STobias Grosser   ///
26979a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
27079a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
27179a947c2STobias Grosser 
272abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
273abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
274abed4969SSiddharth Bhat   /// host pointers to the device.
275abed4969SSiddharth Bhat   /// \note
276abed4969SSiddharth Bhat   /// This is to be used only with managed memory
277abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
278abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
279abed4969SSiddharth Bhat 
28079a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
28179a947c2STobias Grosser   ///
28279a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
28379a947c2STobias Grosser   ///
28479a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
28579a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
28679a947c2STobias Grosser 
287a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
288a90be207SSiddharth Bhat   /// parameters.
289a90be207SSiddharth Bhat   ///
290a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
291a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
292a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
293a90be207SSiddharth Bhat   ///                   parameter.
294a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
295a90be207SSiddharth Bhat                             int Index);
296a90be207SSiddharth Bhat 
29779a947c2STobias Grosser   /// Create kernel launch parameters.
29879a947c2STobias Grosser   ///
29979a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
30079a947c2STobias Grosser   /// @param F             The kernel function that has been created.
30157693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
30279a947c2STobias Grosser   ///
30379a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
30479a947c2STobias Grosser   ///          values that are passed to the kernel.
30557693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
30657693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
30779a947c2STobias Grosser 
308b513b491STobias Grosser   /// Create declarations for kernel variable.
309b513b491STobias Grosser   ///
310b513b491STobias Grosser   /// This includes shared memory declarations.
311b513b491STobias Grosser   ///
312b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
313b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
314b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
315b513b491STobias Grosser 
316c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
317c1c6a2a6STobias Grosser   ///
318c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
319c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
320c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
321c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
322c1c6a2a6STobias Grosser   /// as specified here.
323c1c6a2a6STobias Grosser   ///
324c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
325c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
326c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
327c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
328c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
329c1c6a2a6STobias Grosser                           Value *BlockDimZ);
330c1c6a2a6STobias Grosser 
33132837fe3STobias Grosser   /// Create GPU kernel.
33232837fe3STobias Grosser   ///
33332837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
33432837fe3STobias Grosser   ///
33532837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
33632837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
33732837fe3STobias Grosser 
33813c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
33913c78e4dSTobias Grosser   ///
34013c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
34113c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
34213c78e4dSTobias Grosser 
343aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
344aaabbbf8STobias Grosser   ///
345aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
346aaabbbf8STobias Grosser   ///
347aaabbbf8STobias Grosser   /// Example:
348aaabbbf8STobias Grosser   ///
349aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
350aaabbbf8STobias Grosser   ///     A[i + 42] += ...
351aaabbbf8STobias Grosser   ///
352aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
353aaabbbf8STobias Grosser   ///
354aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
355aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
356aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
357aaabbbf8STobias Grosser 
35800bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
35900bb5a99STobias Grosser   ///
36000bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
36100bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
36200bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
36300bb5a99STobias Grosser 
36432837fe3STobias Grosser   /// Create kernel function.
36532837fe3STobias Grosser   ///
36632837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
36732837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
36832837fe3STobias Grosser   /// start block of this newly created function.
36932837fe3STobias Grosser   ///
37032837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
371edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
372*f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
373*f291c8d5SSiddharth Bhat   ///                         kernel.
374edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
375*f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
376*f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
37732837fe3STobias Grosser 
37832837fe3STobias Grosser   /// Create the declaration of a kernel function.
37932837fe3STobias Grosser   ///
38032837fe3STobias Grosser   /// The kernel function takes as arguments:
38132837fe3STobias Grosser   ///
38232837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
383f6044bd0STobias Grosser   ///   - Host iterators
384c84a1995STobias Grosser   ///   - Parameters
38532837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
38632837fe3STobias Grosser   ///
38732837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
388edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
389edb885cbSTobias Grosser   ///
39032837fe3STobias Grosser   /// @returns The newly declared function.
391edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
392edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
39332837fe3STobias Grosser 
394472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
395472f9654STobias Grosser   ///
396472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
397472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
398472f9654STobias Grosser 
399*f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
400*f291c8d5SSiddharth Bhat   ///
401*f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
402*f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
403*f291c8d5SSiddharth Bhat   ///
404*f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
405*f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
406*f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
407*f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
408*f291c8d5SSiddharth Bhat   ///
409*f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
410*f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
411*f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
412*f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
413*f291c8d5SSiddharth Bhat   ///
414*f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
415*f291c8d5SSiddharth Bhat   ///                         this kernel.
416*f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
417*f291c8d5SSiddharth Bhat 
418b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
419b513b491STobias Grosser   ///
420b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
421b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
422b513b491STobias Grosser 
423edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
424edb885cbSTobias Grosser   ///
425edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
426edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
427edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
428edb885cbSTobias Grosser 
4295260c041STobias Grosser   /// Create an in-kernel synchronization call.
4305260c041STobias Grosser   void createKernelSync();
4315260c041STobias Grosser 
43274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
43374dc3cb4STobias Grosser   ///
43474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
43574dc3cb4STobias Grosser   std::string createKernelASM();
43674dc3cb4STobias Grosser 
43774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
43874dc3cb4STobias Grosser   ///
43974dc3cb4STobias Grosser   /// @param F The function to remove references to.
44074dc3cb4STobias Grosser   void clearDominators(Function *F);
44174dc3cb4STobias Grosser 
44274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
44374dc3cb4STobias Grosser   ///
44474dc3cb4STobias Grosser   /// @param F The function to remove references to.
44574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
44674dc3cb4STobias Grosser 
44774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
44874dc3cb4STobias Grosser   ///
44974dc3cb4STobias Grosser   /// @param F The function to remove references to.
45074dc3cb4STobias Grosser   void clearLoops(Function *F);
45174dc3cb4STobias Grosser 
45232837fe3STobias Grosser   /// Finalize the generation of the kernel function.
45332837fe3STobias Grosser   ///
45432837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
45532837fe3STobias Grosser   /// dump its IR to stderr.
45657793596STobias Grosser   ///
45757793596STobias Grosser   /// @returns The Assembly string of the kernel.
45857793596STobias Grosser   std::string finalizeKernelFunction();
459fa7b0802STobias Grosser 
46051dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
46151dfc275STobias Grosser   ///
46251dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
463a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
46451dfc275STobias Grosser   /// the kernel terminates.
46551dfc275STobias Grosser   ///
46651dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
46751dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
46851dfc275STobias Grosser 
4697287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
470fa7b0802STobias Grosser   void allocateDeviceArrays();
471fa7b0802STobias Grosser 
4727287aeddSTobias Grosser   /// Free all allocated device arrays.
4737287aeddSTobias Grosser   void freeDeviceArrays();
4747287aeddSTobias Grosser 
475fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
476fa7b0802STobias Grosser   ///
477fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
478fa7b0802STobias Grosser   Value *createCallInitContext();
479fa7b0802STobias Grosser 
48079a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
48179a947c2STobias Grosser   ///
48279a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
48379a947c2STobias Grosser   ///
48479a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
48579a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
48679a947c2STobias Grosser 
487fa7b0802STobias Grosser   /// Create a call to free the GPU context.
488fa7b0802STobias Grosser   ///
489fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
490fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
491fa7b0802STobias Grosser 
4927287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
4937287aeddSTobias Grosser   ///
4947287aeddSTobias Grosser   /// @param Size The size of memory to allocate
4957287aeddSTobias Grosser   ///
4967287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
497fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
4987287aeddSTobias Grosser 
4997287aeddSTobias Grosser   /// Create a call to free a device array.
5007287aeddSTobias Grosser   ///
5017287aeddSTobias Grosser   /// @param Array The device array to free.
5027287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
50313c78e4dSTobias Grosser 
50413c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
50513c78e4dSTobias Grosser   ///
50613c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
50713c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
50813c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
50913c78e4dSTobias Grosser                                       Value *Size);
51013c78e4dSTobias Grosser 
51113c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
51213c78e4dSTobias Grosser   ///
51313c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
51413c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
51513c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
51613c78e4dSTobias Grosser                                       Value *Size);
51757793596STobias Grosser 
518abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
519abed4969SSiddharth Bhat   /// \note
520abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
521abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
522abed4969SSiddharth Bhat 
52357793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
52457793596STobias Grosser   ///
52557793596STobias Grosser   /// @param Buffer The string describing the kernel.
52657793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
52757793596STobias Grosser   ///
52857793596STobias Grosser   /// @returns A pointer to a kernel object
52957793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
53057793596STobias Grosser 
53157793596STobias Grosser   /// Create a call to free a GPU kernel.
53257793596STobias Grosser   ///
53357793596STobias Grosser   /// @param GPUKernel THe kernel to free.
53457793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
53579a947c2STobias Grosser 
53679a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
53779a947c2STobias Grosser   ///
53879a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
53979a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
54079a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
54179a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
54279a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
54379a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
544a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
54579a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
54679a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
54779a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
54879a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
54979a947c2STobias Grosser                               Value *Parameters);
5501fb9b64dSTobias Grosser };
5511fb9b64dSTobias Grosser 
552fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
553750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
554750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
555750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
556750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
557750160e2STobias Grosser 
558fa7b0802STobias Grosser   GPUContext = createCallInitContext();
559abed4969SSiddharth Bhat 
560abed4969SSiddharth Bhat   if (!ManagedMemory)
561fa7b0802STobias Grosser     allocateDeviceArrays();
562fa7b0802STobias Grosser }
563fa7b0802STobias Grosser 
564fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
565abed4969SSiddharth Bhat   if (!ManagedMemory)
5667287aeddSTobias Grosser     freeDeviceArrays();
567abed4969SSiddharth Bhat 
568fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
569fa7b0802STobias Grosser   IslNodeBuilder::finalize();
570fa7b0802STobias Grosser }
571fa7b0802STobias Grosser 
572fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
573abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
574abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
575fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
576fa7b0802STobias Grosser 
577fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
578fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
57913c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
5807287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
5817287aeddSTobias Grosser     DevArrayName.append(Array->name);
582fa7b0802STobias Grosser 
58313c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
584aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
585aaabbbf8STobias Grosser     if (Offset)
586aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
587aaabbbf8STobias Grosser           ArraySize,
588aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
589aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
5907287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
5917287aeddSTobias Grosser     DevArray->setName(DevArrayName);
59213c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
593fa7b0802STobias Grosser   }
594fa7b0802STobias Grosser 
595fa7b0802STobias Grosser   isl_ast_build_free(Build);
596fa7b0802STobias Grosser }
597fa7b0802STobias Grosser 
598c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
599c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
600c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
601c1c6a2a6STobias Grosser 
602c1c6a2a6STobias Grosser   for (auto &F : *M) {
603c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
604c1c6a2a6STobias Grosser       continue;
605c1c6a2a6STobias Grosser 
606c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
607c1c6a2a6STobias Grosser 
608c1c6a2a6STobias Grosser     Metadata *Elements[] = {
609c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
610c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
611c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
612c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
613c1c6a2a6STobias Grosser     };
614c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
615c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
616c1c6a2a6STobias Grosser   }
617c1c6a2a6STobias Grosser }
618c1c6a2a6STobias Grosser 
6197287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
620abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
62113c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
62213c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
6237287aeddSTobias Grosser }
6247287aeddSTobias Grosser 
62557793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
62657793596STobias Grosser   const char *Name = "polly_getKernel";
62757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
62857793596STobias Grosser   Function *F = M->getFunction(Name);
62957793596STobias Grosser 
63057793596STobias Grosser   // If F is not available, declare it.
63157793596STobias Grosser   if (!F) {
63257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
63357793596STobias Grosser     std::vector<Type *> Args;
63457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
63657793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
63757793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
63857793596STobias Grosser   }
63957793596STobias Grosser 
64057793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
64157793596STobias Grosser }
64257793596STobias Grosser 
64379a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
64479a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
64579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
64679a947c2STobias Grosser   Function *F = M->getFunction(Name);
64779a947c2STobias Grosser 
64879a947c2STobias Grosser   // If F is not available, declare it.
64979a947c2STobias Grosser   if (!F) {
65079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
65179a947c2STobias Grosser     std::vector<Type *> Args;
65279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
65379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
65479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
65579a947c2STobias Grosser   }
65679a947c2STobias Grosser 
65779a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
65879a947c2STobias Grosser }
65979a947c2STobias Grosser 
66079a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
66179a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
66279a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
66379a947c2STobias Grosser                                             Value *Parameters) {
66479a947c2STobias Grosser   const char *Name = "polly_launchKernel";
66579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
66679a947c2STobias Grosser   Function *F = M->getFunction(Name);
66779a947c2STobias Grosser 
66879a947c2STobias Grosser   // If F is not available, declare it.
66979a947c2STobias Grosser   if (!F) {
67079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
67179a947c2STobias Grosser     std::vector<Type *> Args;
67279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
67479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
67579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
67679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
67779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
67879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
67979a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
68079a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
68179a947c2STobias Grosser   }
68279a947c2STobias Grosser 
683ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
68479a947c2STobias Grosser                          BlockDimZ, Parameters});
68579a947c2STobias Grosser }
68679a947c2STobias Grosser 
68757793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
68857793596STobias Grosser   const char *Name = "polly_freeKernel";
68957793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
69057793596STobias Grosser   Function *F = M->getFunction(Name);
69157793596STobias Grosser 
69257793596STobias Grosser   // If F is not available, declare it.
69357793596STobias Grosser   if (!F) {
69457793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
69557793596STobias Grosser     std::vector<Type *> Args;
69657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
69757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
69857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
69957793596STobias Grosser   }
70057793596STobias Grosser 
70157793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
70257793596STobias Grosser }
70357793596STobias Grosser 
7047287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
705abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
706abed4969SSiddharth Bhat                            "for device");
7077287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
7087287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7097287aeddSTobias Grosser   Function *F = M->getFunction(Name);
7107287aeddSTobias Grosser 
7117287aeddSTobias Grosser   // If F is not available, declare it.
7127287aeddSTobias Grosser   if (!F) {
7137287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
7147287aeddSTobias Grosser     std::vector<Type *> Args;
7157287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
7167287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
7177287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
7187287aeddSTobias Grosser   }
7197287aeddSTobias Grosser 
7207287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
7217287aeddSTobias Grosser }
7227287aeddSTobias Grosser 
723fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
724abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
725abed4969SSiddharth Bhat                            "for device");
726fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
727fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
728fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
729fa7b0802STobias Grosser 
730fa7b0802STobias Grosser   // If F is not available, declare it.
731fa7b0802STobias Grosser   if (!F) {
732fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
733fa7b0802STobias Grosser     std::vector<Type *> Args;
734fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
735fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
736fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
737fa7b0802STobias Grosser   }
738fa7b0802STobias Grosser 
739fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
740fa7b0802STobias Grosser }
741fa7b0802STobias Grosser 
74213c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
74313c78e4dSTobias Grosser                                                     Value *DeviceData,
74413c78e4dSTobias Grosser                                                     Value *Size) {
745abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
746abed4969SSiddharth Bhat                            "device and host");
74713c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
74813c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
74913c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
75013c78e4dSTobias Grosser 
75113c78e4dSTobias Grosser   // If F is not available, declare it.
75213c78e4dSTobias Grosser   if (!F) {
75313c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
75413c78e4dSTobias Grosser     std::vector<Type *> Args;
75513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
75613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
75713c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
75813c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
75913c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
76013c78e4dSTobias Grosser   }
76113c78e4dSTobias Grosser 
76213c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
76313c78e4dSTobias Grosser }
76413c78e4dSTobias Grosser 
76513c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
76613c78e4dSTobias Grosser                                                     Value *HostData,
76713c78e4dSTobias Grosser                                                     Value *Size) {
768abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
769abed4969SSiddharth Bhat                            "device and host");
77013c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
77113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
77213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
77313c78e4dSTobias Grosser 
77413c78e4dSTobias Grosser   // If F is not available, declare it.
77513c78e4dSTobias Grosser   if (!F) {
77613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
77713c78e4dSTobias Grosser     std::vector<Type *> Args;
77813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
77913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
78013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
78113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
78213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
78313c78e4dSTobias Grosser   }
78413c78e4dSTobias Grosser 
78513c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
78613c78e4dSTobias Grosser }
78713c78e4dSTobias Grosser 
788abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
789abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
790abed4969SSiddharth Bhat                           "managed memory");
791abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
792abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
793abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
794abed4969SSiddharth Bhat 
795abed4969SSiddharth Bhat   // If F is not available, declare it.
796abed4969SSiddharth Bhat   if (!F) {
797abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
798abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
799abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
800abed4969SSiddharth Bhat   }
801abed4969SSiddharth Bhat 
802abed4969SSiddharth Bhat   Builder.CreateCall(F);
803abed4969SSiddharth Bhat }
804abed4969SSiddharth Bhat 
805fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
80617f01968SSiddharth Bhat   const char *Name;
80717f01968SSiddharth Bhat 
80817f01968SSiddharth Bhat   switch (Runtime) {
80917f01968SSiddharth Bhat   case GPURuntime::CUDA:
81017f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
81117f01968SSiddharth Bhat     break;
81217f01968SSiddharth Bhat   case GPURuntime::OpenCL:
81317f01968SSiddharth Bhat     Name = "polly_initContextCL";
81417f01968SSiddharth Bhat     break;
81517f01968SSiddharth Bhat   }
81617f01968SSiddharth Bhat 
817fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
818fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
819fa7b0802STobias Grosser 
820fa7b0802STobias Grosser   // If F is not available, declare it.
821fa7b0802STobias Grosser   if (!F) {
822fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
823fa7b0802STobias Grosser     std::vector<Type *> Args;
824fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
825fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
826fa7b0802STobias Grosser   }
827fa7b0802STobias Grosser 
828fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
829fa7b0802STobias Grosser }
830fa7b0802STobias Grosser 
831fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
832fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
833fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
834fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
835fa7b0802STobias Grosser 
836fa7b0802STobias Grosser   // If F is not available, declare it.
837fa7b0802STobias Grosser   if (!F) {
838fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
839fa7b0802STobias Grosser     std::vector<Type *> Args;
840fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
841fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
842fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
843fa7b0802STobias Grosser   }
844fa7b0802STobias Grosser 
845fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
846fa7b0802STobias Grosser }
847fa7b0802STobias Grosser 
8485260c041STobias Grosser /// Check if one string is a prefix of another.
8495260c041STobias Grosser ///
8505260c041STobias Grosser /// @param String The string in which to look for the prefix.
8515260c041STobias Grosser /// @param Prefix The prefix to look for.
8525260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
8535260c041STobias Grosser   return String.find(Prefix) == 0;
8545260c041STobias Grosser }
8555260c041STobias Grosser 
85613c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
85713c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
85813c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
85913c78e4dSTobias Grosser 
86013c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
86113c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
86213c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
86313c78e4dSTobias Grosser 
86413c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
86513c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
86613c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
86713c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
86813c78e4dSTobias Grosser     }
86913c78e4dSTobias Grosser 
87013c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
871b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
872b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
87313c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
87413c78e4dSTobias Grosser   }
87513c78e4dSTobias Grosser   isl_ast_build_free(Build);
87613c78e4dSTobias Grosser   return ArraySize;
87713c78e4dSTobias Grosser }
87813c78e4dSTobias Grosser 
879aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
880aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
881aaabbbf8STobias Grosser     return nullptr;
882aaabbbf8STobias Grosser 
883aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
884aaabbbf8STobias Grosser 
885aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
886aaabbbf8STobias Grosser 
887aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
888aaabbbf8STobias Grosser 
889aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
890aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
891aaabbbf8STobias Grosser 
892aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
893aaabbbf8STobias Grosser     isl_set_free(Min);
894aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
895aaabbbf8STobias Grosser     isl_ast_build_free(Build);
896aaabbbf8STobias Grosser     return nullptr;
897aaabbbf8STobias Grosser   }
898aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
899aaabbbf8STobias Grosser 
900aaabbbf8STobias Grosser   isl_ast_expr *Result =
901aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
902aaabbbf8STobias Grosser 
903aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
904aaabbbf8STobias Grosser     if (i > 0) {
905aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
906aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
907aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
908aaabbbf8STobias Grosser     }
909aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
910aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
911aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
912aaabbbf8STobias Grosser   }
913aaabbbf8STobias Grosser 
914aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
915aaabbbf8STobias Grosser   isl_set_free(Min);
916aaabbbf8STobias Grosser   isl_ast_build_free(Build);
917aaabbbf8STobias Grosser 
918aaabbbf8STobias Grosser   return ResultValue;
919aaabbbf8STobias Grosser }
920aaabbbf8STobias Grosser 
921abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
922abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
923abed4969SSiddharth Bhat 
924abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
925abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
926abed4969SSiddharth Bhat                           "with managed memory");
927abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
928abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
929abed4969SSiddharth Bhat     return it->second;
930abed4969SSiddharth Bhat   } else {
931abed4969SSiddharth Bhat     Value *HostPtr;
932abed4969SSiddharth Bhat 
933abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
934abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
935abed4969SSiddharth Bhat     else
936abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
937abed4969SSiddharth Bhat 
938abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
939abed4969SSiddharth Bhat     if (Offset) {
940abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
941abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
942abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
943abed4969SSiddharth Bhat     }
944abed4969SSiddharth Bhat 
945abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
946abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
947abed4969SSiddharth Bhat     return HostPtr;
948abed4969SSiddharth Bhat   }
949abed4969SSiddharth Bhat }
950abed4969SSiddharth Bhat 
95113c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
95213c78e4dSTobias Grosser                                         enum DataDirection Direction) {
953abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
95413c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
95513c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
95613c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
95713c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
95813c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
95913c78e4dSTobias Grosser 
96013c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
961aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
96213c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
96313c78e4dSTobias Grosser 
964b06ff457STobias Grosser   Value *HostPtr;
965b06ff457STobias Grosser 
966b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
967b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
968b06ff457STobias Grosser   else
969b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
97013c78e4dSTobias Grosser 
971aaabbbf8STobias Grosser   if (Offset) {
972aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
973aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
974aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
975aaabbbf8STobias Grosser   }
976aaabbbf8STobias Grosser 
97713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
97813c78e4dSTobias Grosser 
979aaabbbf8STobias Grosser   if (Offset) {
980aaabbbf8STobias Grosser     Size = Builder.CreateSub(
981ff40087aSTobias Grosser         Size, Builder.CreateMul(
982ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
983aaabbbf8STobias Grosser   }
984aaabbbf8STobias Grosser 
98513c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
98613c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
98713c78e4dSTobias Grosser   else
98813c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
98913c78e4dSTobias Grosser 
99013c78e4dSTobias Grosser   isl_id_free(Id);
99113c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
99213c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
99313c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
99413c78e4dSTobias Grosser }
99513c78e4dSTobias Grosser 
9961fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
99732837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
99832837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
99932837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
100032837fe3STobias Grosser   isl_id_free(Id);
100132837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
100232837fe3STobias Grosser 
100332837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
100432837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
100532837fe3STobias Grosser     createKernel(UserStmt);
100632837fe3STobias Grosser     isl_ast_expr_free(Expr);
100732837fe3STobias Grosser     return;
100832837fe3STobias Grosser   }
100932837fe3STobias Grosser 
101013c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1011abed4969SSiddharth Bhat     if (!ManagedMemory)
101213c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1013abed4969SSiddharth Bhat     else
1014abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1015abed4969SSiddharth Bhat 
101632837fe3STobias Grosser     isl_ast_expr_free(Expr);
101713c78e4dSTobias Grosser     return;
101813c78e4dSTobias Grosser   }
101913c78e4dSTobias Grosser 
102013c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1021abed4969SSiddharth Bhat     if (!ManagedMemory) {
102213c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1023abed4969SSiddharth Bhat     } else {
1024abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1025abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1026abed4969SSiddharth Bhat     }
102713c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
102838fc0aedSTobias Grosser     return;
102938fc0aedSTobias Grosser   }
103038fc0aedSTobias Grosser 
10315260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
10325260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
10335260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
10345260c041STobias Grosser   isl_id_free(Anno);
10355260c041STobias Grosser 
10365260c041STobias Grosser   switch (KernelStmt->type) {
10375260c041STobias Grosser   case ppcg_kernel_domain:
1038edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
10395260c041STobias Grosser     isl_ast_node_free(UserStmt);
10405260c041STobias Grosser     return;
10415260c041STobias Grosser   case ppcg_kernel_copy:
1042b513b491STobias Grosser     createKernelCopy(KernelStmt);
10435260c041STobias Grosser     isl_ast_expr_free(Expr);
10445260c041STobias Grosser     isl_ast_node_free(UserStmt);
10455260c041STobias Grosser     return;
10465260c041STobias Grosser   case ppcg_kernel_sync:
10475260c041STobias Grosser     createKernelSync();
10485260c041STobias Grosser     isl_ast_expr_free(Expr);
10495260c041STobias Grosser     isl_ast_node_free(UserStmt);
10505260c041STobias Grosser     return;
10515260c041STobias Grosser   }
10525260c041STobias Grosser 
10535260c041STobias Grosser   isl_ast_expr_free(Expr);
10545260c041STobias Grosser   isl_ast_node_free(UserStmt);
10555260c041STobias Grosser   return;
10565260c041STobias Grosser }
1057b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1058b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1059b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1060b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1061b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1062b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1063b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1064b513b491STobias Grosser 
1065b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1066b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1067b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1068b513b491STobias Grosser   } else {
1069b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1070b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1071b513b491STobias Grosser   }
1072b513b491STobias Grosser }
10735260c041STobias Grosser 
1074edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1075edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1076edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1077edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1078edb885cbSTobias Grosser 
1079edb885cbSTobias Grosser   LoopToScevMapT LTS;
1080edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1081edb885cbSTobias Grosser 
1082edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1083edb885cbSTobias Grosser 
1084edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1085edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1086edb885cbSTobias Grosser   else
1087a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1088edb885cbSTobias Grosser }
1089edb885cbSTobias Grosser 
10905260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
10915260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
109217f01968SSiddharth Bhat 
109317f01968SSiddharth Bhat   Function *Sync;
109417f01968SSiddharth Bhat 
109517f01968SSiddharth Bhat   switch (Arch) {
109617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
109717f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
109817f01968SSiddharth Bhat     break;
109917f01968SSiddharth Bhat   }
110017f01968SSiddharth Bhat 
11015260c041STobias Grosser   Builder.CreateCall(Sync, {});
11025260c041STobias Grosser }
11035260c041STobias Grosser 
1104edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1105edb885cbSTobias Grosser ///
1106edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1107edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1108edb885cbSTobias Grosser ///
1109edb885cbSTobias Grosser /// @param Node The node to collect references for.
1110edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1111edb885cbSTobias Grosser ///
1112edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1113edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1114edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1115edb885cbSTobias Grosser     return isl_bool_true;
1116edb885cbSTobias Grosser 
1117edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1118edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1119edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1120edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1121edb885cbSTobias Grosser   isl_id_free(Id);
1122edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1123edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1124edb885cbSTobias Grosser 
1125edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1126edb885cbSTobias Grosser     return isl_bool_true;
1127edb885cbSTobias Grosser 
1128edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1129edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1130edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1131edb885cbSTobias Grosser   isl_id_free(Id);
1132edb885cbSTobias Grosser 
113300bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1134edb885cbSTobias Grosser 
1135edb885cbSTobias Grosser   return isl_bool_true;
1136edb885cbSTobias Grosser }
1137edb885cbSTobias Grosser 
1138*f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
1139*f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) {
1140*f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1141*f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
1142*f291c8d5SSiddharth Bhat   // all variants of the intrinsic "llvm.sqrt.*"
1143*f291c8d5SSiddharth Bhat   return F->isIntrinsic() && F->getName().startswith("llvm.sqrt");
1144*f291c8d5SSiddharth Bhat }
1145*f291c8d5SSiddharth Bhat 
1146*f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1147*f291c8d5SSiddharth Bhat ///
1148*f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1149*f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1150*f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1151*f291c8d5SSiddharth Bhat /// `Function`s.
1152*f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1153*f291c8d5SSiddharth Bhat 
1154*f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1155*f291c8d5SSiddharth Bhat static SetVector<Function *>
1156*f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1157*f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1158*f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1159*f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1160*f291c8d5SSiddharth Bhat     if (F) {
1161*f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1162*f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1163*f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1164*f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1165*f291c8d5SSiddharth Bhat     }
1166*f291c8d5SSiddharth Bhat   }
1167*f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1168*f291c8d5SSiddharth Bhat }
1169*f291c8d5SSiddharth Bhat 
1170*f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1171*f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1172edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1173edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1174edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1175edb885cbSTobias Grosser   SubtreeReferences References = {
1176edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1177edb885cbSTobias Grosser 
1178edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1179edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1180edb885cbSTobias Grosser 
1181edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1182edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1183edb885cbSTobias Grosser 
1184edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1185edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1186edb885cbSTobias Grosser 
1187edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1188d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1189edb885cbSTobias Grosser 
1190edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1191edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1192edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1193edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1194edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1195edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1196edb885cbSTobias Grosser     isl_id_free(Id);
1197edb885cbSTobias Grosser   }
1198edb885cbSTobias Grosser   isl_space_free(Space);
1199edb885cbSTobias Grosser 
1200edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1201edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1202edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1203edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1204edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1205edb885cbSTobias Grosser     isl_id_free(Id);
1206edb885cbSTobias Grosser   }
1207edb885cbSTobias Grosser 
1208*f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1209*f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1210*f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1211*f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1212*f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1213*f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1214*f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1215*f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1216*f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1217*f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1218*f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1219*f291c8d5SSiddharth Bhat 
1220*f291c8d5SSiddharth Bhat   return std::make_pair(ValidSubtreeValues, ValidSubtreeFunctions);
1221edb885cbSTobias Grosser }
1222edb885cbSTobias Grosser 
122374dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
122474dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
122574dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
122674dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
122774dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
122874dc3cb4STobias Grosser 
122974dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
123074dc3cb4STobias Grosser     DT.eraseNode(BB);
123174dc3cb4STobias Grosser }
123274dc3cb4STobias Grosser 
123374dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
123474dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
123574dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
123674dc3cb4STobias Grosser     if (L)
123774dc3cb4STobias Grosser       SE.forgetLoop(L);
123874dc3cb4STobias Grosser   }
123974dc3cb4STobias Grosser }
124074dc3cb4STobias Grosser 
124174dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
124274dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
124374dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
124474dc3cb4STobias Grosser     if (L)
124574dc3cb4STobias Grosser       SE.forgetLoop(L);
124674dc3cb4STobias Grosser     LI.removeBlock(&BB);
124774dc3cb4STobias Grosser   }
124874dc3cb4STobias Grosser }
124974dc3cb4STobias Grosser 
125079a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
125179a947c2STobias Grosser   std::vector<Value *> Sizes;
125279a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
125379a947c2STobias Grosser 
125479a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
125579a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
125679a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
125779a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
125879a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
125979a947c2STobias Grosser     Sizes.push_back(Res);
126079a947c2STobias Grosser   }
126179a947c2STobias Grosser   isl_ast_build_free(Context);
126279a947c2STobias Grosser 
126379a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
126479a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
126579a947c2STobias Grosser 
126679a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
126779a947c2STobias Grosser }
126879a947c2STobias Grosser 
126979a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
127079a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
127179a947c2STobias Grosser   std::vector<Value *> Sizes;
127279a947c2STobias Grosser 
127379a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
127479a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
127579a947c2STobias Grosser     Sizes.push_back(Res);
127679a947c2STobias Grosser   }
127779a947c2STobias Grosser 
127879a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
127979a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
128079a947c2STobias Grosser 
128179a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
128279a947c2STobias Grosser }
128379a947c2STobias Grosser 
1284a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1285a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1286a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1287a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1288a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1289a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1290a90be207SSiddharth Bhat }
1291a90be207SSiddharth Bhat 
129257693272STobias Grosser Value *
129357693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
129457693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1295a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1296a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1297a90be207SSiddharth Bhat 
1298a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
129979a947c2STobias Grosser 
130079a947c2STobias Grosser   BasicBlock *EntryBlock =
130179a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
130267726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
130379a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
130467726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
130567726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
130679a947c2STobias Grosser 
130779a947c2STobias Grosser   int Index = 0;
130879a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
130979a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
131079a947c2STobias Grosser       continue;
131179a947c2STobias Grosser 
131279a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
131379a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
131479a947c2STobias Grosser 
1315a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1316a90be207SSiddharth Bhat 
1317abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1318abed4969SSiddharth Bhat     if (ManagedMemory) {
1319abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1320abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1321abed4969SSiddharth Bhat     } else {
1322abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
132379a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1324abed4969SSiddharth Bhat     }
1325abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1326abed4969SSiddharth Bhat                                   "initialized");
1327aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1328aaabbbf8STobias Grosser 
1329aaabbbf8STobias Grosser     if (Offset) {
1330aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1331aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1332aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1333aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1334aaabbbf8STobias Grosser     }
1335fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1336fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1337aaabbbf8STobias Grosser 
1338fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1339abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1340abed4969SSiddharth Bhat       if (ManagedMemory)
1341abed4969SSiddharth Bhat         ValPtr = DevArray;
1342abed4969SSiddharth Bhat       else
1343abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1344abed4969SSiddharth Bhat 
1345abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1346abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1347fe74a7a1STobias Grosser       Value *ValPtrCast =
1348fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1349fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1350fe74a7a1STobias Grosser     } else {
135167726b32STobias Grosser       Instruction *Param =
135267726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
135367726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
135479a947c2STobias Grosser                          EntryBlock->getTerminator());
135579a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
135679a947c2STobias Grosser       Value *ParamTyped =
135779a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
135879a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1359fe74a7a1STobias Grosser     }
136079a947c2STobias Grosser     Index++;
136179a947c2STobias Grosser   }
136279a947c2STobias Grosser 
1363a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1364a490147cSTobias Grosser 
1365a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1366a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1367a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1368a490147cSTobias Grosser     isl_id_free(Id);
1369a90be207SSiddharth Bhat 
1370a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1371a90be207SSiddharth Bhat 
137267726b32STobias Grosser     Instruction *Param =
137367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
137467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1375a490147cSTobias Grosser                        EntryBlock->getTerminator());
1376a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1377a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1378a490147cSTobias Grosser     Index++;
1379a490147cSTobias Grosser   }
1380a490147cSTobias Grosser 
1381d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1382d8b94bcaSTobias Grosser 
1383d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1384d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1385d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1386d8b94bcaSTobias Grosser     isl_id_free(Id);
1387a90be207SSiddharth Bhat 
1388a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1389a90be207SSiddharth Bhat 
139067726b32STobias Grosser     Instruction *Param =
139167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
139267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1393d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1394d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1395a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1396d8b94bcaSTobias Grosser     Index++;
1397d8b94bcaSTobias Grosser   }
1398d8b94bcaSTobias Grosser 
139957693272STobias Grosser   for (auto Val : SubtreeValues) {
1400a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1401a90be207SSiddharth Bhat 
140267726b32STobias Grosser     Instruction *Param =
140367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
140467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
140557693272STobias Grosser                        EntryBlock->getTerminator());
140657693272STobias Grosser     Builder.CreateStore(Val, Param);
1407a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1408a90be207SSiddharth Bhat     Index++;
1409a90be207SSiddharth Bhat   }
1410a90be207SSiddharth Bhat 
1411a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1412a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1413a90be207SSiddharth Bhat     Instruction *Param =
1414a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1415a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1416a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1417a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1418a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
141957693272STobias Grosser     Index++;
142057693272STobias Grosser   }
142157693272STobias Grosser 
142279a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
142379a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
142479a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
142579a947c2STobias Grosser }
142679a947c2STobias Grosser 
1427*f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1428*f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1429*f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1430*f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1431*f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1432*f291c8d5SSiddharth Bhat     if (!Clone)
1433*f291c8d5SSiddharth Bhat       Clone =
1434*f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1435*f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1436*f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1437*f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1438*f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1439*f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1440*f291c8d5SSiddharth Bhat   }
1441*f291c8d5SSiddharth Bhat }
144232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
144332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
144432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
144532837fe3STobias Grosser   isl_id_free(Id);
144632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
144732837fe3STobias Grosser 
1448bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1449bc653f20STobias Grosser     DeepestParallel =
1450bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1451bc653f20STobias Grosser   else
1452bc653f20STobias Grosser     DeepestSequential =
1453bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1454bc653f20STobias Grosser 
1455c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1456c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1457c1c6a2a6STobias Grosser 
1458*f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1459*f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1460*f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1461edb885cbSTobias Grosser 
146232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
146332837fe3STobias Grosser 
146432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1465472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1466edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1467587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1468b06ff457STobias Grosser   ScalarMap.clear();
146932837fe3STobias Grosser 
1470edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1471edb885cbSTobias Grosser 
1472edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1473edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1474edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1475edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1476edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1477edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1478edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1479edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1480edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1481edb885cbSTobias Grosser     SubtreeValues.insert(V);
1482edb885cbSTobias Grosser   }
1483edb885cbSTobias Grosser 
1484*f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1485*f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
148632837fe3STobias Grosser 
148759ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
148859ab0705STobias Grosser 
148951dfc275STobias Grosser   finalizeKernelArguments(Kernel);
149074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1491c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
149274dc3cb4STobias Grosser   clearDominators(F);
149374dc3cb4STobias Grosser   clearScalarEvolution(F);
149474dc3cb4STobias Grosser   clearLoops(F);
149574dc3cb4STobias Grosser 
1496472f9654STobias Grosser   IDToValue = HostIDs;
149732837fe3STobias Grosser 
1498b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1499b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1500edb885cbSTobias Grosser   EscapeMap.clear();
1501edb885cbSTobias Grosser   IDToSAI.clear();
150274dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
150374dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
15044d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
150574dc3cb4STobias Grosser   LocalArrays.clear();
1506edb885cbSTobias Grosser 
150751dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
150851dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
150957693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
151079a947c2STobias Grosser 
151157793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
151257793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
151357793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
151457793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
151579a947c2STobias Grosser 
151679a947c2STobias Grosser   Value *GridDimX, *GridDimY;
151779a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
151879a947c2STobias Grosser 
151979a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
152079a947c2STobias Grosser                          BlockDimZ, Parameters);
152157793596STobias Grosser   createCallFreeKernel(GPUKernel);
1522b513b491STobias Grosser 
1523b513b491STobias Grosser   for (auto Id : KernelIds)
1524b513b491STobias Grosser     isl_id_free(Id);
1525b513b491STobias Grosser 
1526b513b491STobias Grosser   KernelIds.clear();
152732837fe3STobias Grosser }
152832837fe3STobias Grosser 
152932837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
153032837fe3STobias Grosser ///
153132837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
153232837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1533d277fedaSSiddharth Bhat   std::string Ret = "";
153432837fe3STobias Grosser 
1535d277fedaSSiddharth Bhat   if (!is64Bit) {
1536d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1537d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1538d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1539d277fedaSSiddharth Bhat   } else {
1540d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1541d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1542d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1543d277fedaSSiddharth Bhat   }
154432837fe3STobias Grosser 
154532837fe3STobias Grosser   return Ret;
154632837fe3STobias Grosser }
154732837fe3STobias Grosser 
1548edb885cbSTobias Grosser Function *
1549edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1550edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
155132837fe3STobias Grosser   std::vector<Type *> Args;
155232837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
155332837fe3STobias Grosser 
155432837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
155532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
155632837fe3STobias Grosser       continue;
155732837fe3STobias Grosser 
1558fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1559fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1560fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1561fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1562fe74a7a1STobias Grosser     } else {
1563d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1564d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
156532837fe3STobias Grosser     }
1566fe74a7a1STobias Grosser   }
156732837fe3STobias Grosser 
1568f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1569f6044bd0STobias Grosser 
1570f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1571f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1572f6044bd0STobias Grosser 
1573c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1574c84a1995STobias Grosser 
1575cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1576cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1577cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1578cf66ef26STobias Grosser     isl_id_free(Id);
1579cf66ef26STobias Grosser     Args.push_back(Val->getType());
1580cf66ef26STobias Grosser   }
1581c84a1995STobias Grosser 
1582edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1583edb885cbSTobias Grosser     Args.push_back(V->getType());
1584edb885cbSTobias Grosser 
158532837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
158632837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
158732837fe3STobias Grosser                               GPUModule.get());
158817f01968SSiddharth Bhat 
158917f01968SSiddharth Bhat   switch (Arch) {
159017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
159132837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
159217f01968SSiddharth Bhat     break;
159317f01968SSiddharth Bhat   }
159432837fe3STobias Grosser 
159532837fe3STobias Grosser   auto Arg = FN->arg_begin();
159632837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
159732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
159832837fe3STobias Grosser       continue;
159932837fe3STobias Grosser 
1600edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1601edb885cbSTobias Grosser 
1602edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1603edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1604edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1605edb885cbSTobias Grosser     Value *Val = &*Arg;
1606edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1607edb885cbSTobias Grosser     isl_ast_build *Build =
1608edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1609f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1610edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1611edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1612edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1613edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1614edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1615edb885cbSTobias Grosser     }
1616edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
16174d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
161874dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1619edb885cbSTobias Grosser 
1620edb885cbSTobias Grosser     isl_ast_build_free(Build);
1621b513b491STobias Grosser     KernelIds.push_back(Id);
1622edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
162332837fe3STobias Grosser     Arg++;
162432837fe3STobias Grosser   }
162532837fe3STobias Grosser 
1626f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1627f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1628f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1629f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1630f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1631f6044bd0STobias Grosser     Arg++;
1632f6044bd0STobias Grosser   }
1633f6044bd0STobias Grosser 
1634c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1635c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1636c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
163712453403STobias Grosser     Value *Val = IDToValue[Id];
163812453403STobias Grosser     ValueMap[Val] = &*Arg;
1639c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1640c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1641c84a1995STobias Grosser     Arg++;
1642c84a1995STobias Grosser   }
1643c84a1995STobias Grosser 
1644edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1645edb885cbSTobias Grosser     Arg->setName(V->getName());
1646edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1647edb885cbSTobias Grosser     Arg++;
1648edb885cbSTobias Grosser   }
1649edb885cbSTobias Grosser 
165032837fe3STobias Grosser   return FN;
165132837fe3STobias Grosser }
165232837fe3STobias Grosser 
1653472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
165417f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
165517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1656472f9654STobias Grosser 
165717f01968SSiddharth Bhat   switch (Arch) {
165817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
165917f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
166017f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
166117f01968SSiddharth Bhat 
166217f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
166317f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
166417f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
166517f01968SSiddharth Bhat     break;
166617f01968SSiddharth Bhat   }
1667472f9654STobias Grosser 
1668472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1669472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1670472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1671472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1672472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1673472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1674472f9654STobias Grosser     IDToValue[Id] = Val;
1675472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1676472f9654STobias Grosser   };
1677472f9654STobias Grosser 
1678472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1679472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1680472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1681472f9654STobias Grosser   }
1682472f9654STobias Grosser 
1683472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1684472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1685472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1686472f9654STobias Grosser   }
1687472f9654STobias Grosser }
1688472f9654STobias Grosser 
168900bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
169000bb5a99STobias Grosser   auto Arg = FN->arg_begin();
169100bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
169200bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
169300bb5a99STobias Grosser       continue;
169400bb5a99STobias Grosser 
169500bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
169600bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
169700bb5a99STobias Grosser     isl_id_free(Id);
169800bb5a99STobias Grosser 
169900bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
170000bb5a99STobias Grosser       Arg++;
170100bb5a99STobias Grosser       continue;
170200bb5a99STobias Grosser     }
170300bb5a99STobias Grosser 
1704fe74a7a1STobias Grosser     Value *Val = &*Arg;
1705fe74a7a1STobias Grosser 
1706fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
170700bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1708fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1709fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1710fe74a7a1STobias Grosser     }
1711fe74a7a1STobias Grosser 
1712fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
171300bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
171400bb5a99STobias Grosser 
171500bb5a99STobias Grosser     Arg++;
171600bb5a99STobias Grosser   }
171700bb5a99STobias Grosser }
171800bb5a99STobias Grosser 
171951dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
172051dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
172151dfc275STobias Grosser   auto Arg = FN->arg_begin();
172251dfc275STobias Grosser 
172351dfc275STobias Grosser   bool StoredScalar = false;
172451dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
172551dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
172651dfc275STobias Grosser       continue;
172751dfc275STobias Grosser 
172851dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
172951dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
173051dfc275STobias Grosser     isl_id_free(Id);
173151dfc275STobias Grosser 
173251dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
173351dfc275STobias Grosser       Arg++;
173451dfc275STobias Grosser       continue;
173551dfc275STobias Grosser     }
173651dfc275STobias Grosser 
173751dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
173851dfc275STobias Grosser       Arg++;
173951dfc275STobias Grosser       continue;
174051dfc275STobias Grosser     }
174151dfc275STobias Grosser 
174251dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
174351dfc275STobias Grosser     Value *ArgPtr = &*Arg;
174451dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
174551dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
174651dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
174751dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
174851dfc275STobias Grosser     StoredScalar = true;
174951dfc275STobias Grosser 
175051dfc275STobias Grosser     Arg++;
175151dfc275STobias Grosser   }
175251dfc275STobias Grosser 
175351dfc275STobias Grosser   if (StoredScalar)
175451dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
175551dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
175651dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
175751dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
175851dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
175951dfc275STobias Grosser       BuildSuccessful = 0;
176051dfc275STobias Grosser }
176151dfc275STobias Grosser 
1762b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1763b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1764b513b491STobias Grosser 
1765b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1766b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1767b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1768b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1769b513b491STobias Grosser 
1770f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1771b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1772b513b491STobias Grosser 
1773f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1774928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1775b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1776f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1777b513b491STobias Grosser       isl_val_free(Val);
1778b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1779928d7573STobias Grosser     }
1780928d7573STobias Grosser 
1781928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1782928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1783928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1784928d7573STobias Grosser       isl_val_free(Val);
1785b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1786b513b491STobias Grosser     }
1787b513b491STobias Grosser 
1788130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1789130ca30fSTobias Grosser     Value *Allocation;
1790130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1791130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1792130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1793130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1794130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1795f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1796f919d8b3STobias Grosser 
1797130ca30fSTobias Grosser       Allocation = GlobalVar;
1798130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1799130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1800130ca30fSTobias Grosser     } else {
1801130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1802130ca30fSTobias Grosser     }
18034d5a9172STobias Grosser     SAI =
18044d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1805b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1806130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1807130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1808b513b491STobias Grosser     KernelIds.push_back(Id);
1809b513b491STobias Grosser     IDToSAI[Id] = SAI;
1810b513b491STobias Grosser   }
1811b513b491STobias Grosser }
1812b513b491STobias Grosser 
1813*f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
1814*f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1815*f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
181632837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
181732837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
181817f01968SSiddharth Bhat 
181917f01968SSiddharth Bhat   switch (Arch) {
182017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
182117f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
182232837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
182317f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
182417f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
182532837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
182617f01968SSiddharth Bhat     break;
182717f01968SSiddharth Bhat   }
182832837fe3STobias Grosser 
1829edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
183032837fe3STobias Grosser 
183159ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
183232837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
183332837fe3STobias Grosser 
183459ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
183559ab0705STobias Grosser 
183632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
183732837fe3STobias Grosser   Builder.CreateRetVoid();
183832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1839472f9654STobias Grosser 
1840629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1841629109b6STobias Grosser 
184200bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1843b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1844472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
184532837fe3STobias Grosser }
184632837fe3STobias Grosser 
184774dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
184817f01968SSiddharth Bhat   llvm::Triple GPUTriple;
184917f01968SSiddharth Bhat 
185017f01968SSiddharth Bhat   switch (Arch) {
185117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
185217f01968SSiddharth Bhat     switch (Runtime) {
185317f01968SSiddharth Bhat     case GPURuntime::CUDA:
185417f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
185517f01968SSiddharth Bhat       break;
185617f01968SSiddharth Bhat     case GPURuntime::OpenCL:
185717f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
185817f01968SSiddharth Bhat       break;
185917f01968SSiddharth Bhat     }
186017f01968SSiddharth Bhat     break;
186117f01968SSiddharth Bhat   }
186217f01968SSiddharth Bhat 
186374dc3cb4STobias Grosser   std::string ErrMsg;
186474dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
186574dc3cb4STobias Grosser 
186674dc3cb4STobias Grosser   if (!GPUTarget) {
186774dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
186874dc3cb4STobias Grosser     return "";
186974dc3cb4STobias Grosser   }
187074dc3cb4STobias Grosser 
187174dc3cb4STobias Grosser   TargetOptions Options;
187274dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
187317f01968SSiddharth Bhat 
187417f01968SSiddharth Bhat   std::string subtarget;
187517f01968SSiddharth Bhat 
187617f01968SSiddharth Bhat   switch (Arch) {
187717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
187817f01968SSiddharth Bhat     subtarget = CudaVersion;
187917f01968SSiddharth Bhat     break;
188017f01968SSiddharth Bhat   }
188117f01968SSiddharth Bhat 
188217f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
188317f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
188474dc3cb4STobias Grosser 
188574dc3cb4STobias Grosser   SmallString<0> ASMString;
188674dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
188774dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
188874dc3cb4STobias Grosser 
188974dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
189074dc3cb4STobias Grosser 
189174dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
189274dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
189374dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
189474dc3cb4STobias Grosser     return "";
189574dc3cb4STobias Grosser   }
189674dc3cb4STobias Grosser 
189774dc3cb4STobias Grosser   PM.run(*GPUModule);
189874dc3cb4STobias Grosser 
189974dc3cb4STobias Grosser   return ASMStream.str();
190074dc3cb4STobias Grosser }
190174dc3cb4STobias Grosser 
190257793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
19035857b701STobias Grosser   if (verifyModule(*GPUModule)) {
19045857b701STobias Grosser     BuildSuccessful = false;
19055857b701STobias Grosser     return "";
19065857b701STobias Grosser   }
190732837fe3STobias Grosser 
190832837fe3STobias Grosser   if (DumpKernelIR)
190932837fe3STobias Grosser     outs() << *GPUModule << "\n";
191032837fe3STobias Grosser 
19119a18d559STobias Grosser   // Optimize module.
19129a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
19139a18d559STobias Grosser   PassManagerBuilder PassBuilder;
19149a18d559STobias Grosser   PassBuilder.OptLevel = 3;
19159a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
19169a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
19179a18d559STobias Grosser   OptPasses.run(*GPUModule);
19189a18d559STobias Grosser 
191974dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
192074dc3cb4STobias Grosser 
192174dc3cb4STobias Grosser   if (DumpKernelASM)
192274dc3cb4STobias Grosser     outs() << Assembly << "\n";
192374dc3cb4STobias Grosser 
192432837fe3STobias Grosser   GPUModule.release();
1925472f9654STobias Grosser   KernelIDs.clear();
192657793596STobias Grosser 
192757793596STobias Grosser   return Assembly;
192832837fe3STobias Grosser }
192932837fe3STobias Grosser 
19309dfe4e7cSTobias Grosser namespace {
19319dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
19329dfe4e7cSTobias Grosser public:
19339dfe4e7cSTobias Grosser   static char ID;
19349dfe4e7cSTobias Grosser 
193517f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
193617f01968SSiddharth Bhat 
193717f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
193817f01968SSiddharth Bhat 
1939e938517eSTobias Grosser   /// The scop that is currently processed.
1940e938517eSTobias Grosser   Scop *S;
1941e938517eSTobias Grosser 
194238fc0aedSTobias Grosser   LoopInfo *LI;
194338fc0aedSTobias Grosser   DominatorTree *DT;
194438fc0aedSTobias Grosser   ScalarEvolution *SE;
194538fc0aedSTobias Grosser   const DataLayout *DL;
194638fc0aedSTobias Grosser   RegionInfo *RI;
194738fc0aedSTobias Grosser 
19489dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
19499dfe4e7cSTobias Grosser 
1950e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1951e938517eSTobias Grosser   ///
1952e938517eSTobias Grosser   /// @returns The compilation options.
1953e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1954e938517eSTobias Grosser     auto DebugOptions =
1955e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1956e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1957e938517eSTobias Grosser 
1958e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1959e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1960e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1961e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
19628950ceadSTobias Grosser     DebugOptions->verbose = false;
1963e938517eSTobias Grosser 
1964e938517eSTobias Grosser     Options->debug = DebugOptions;
1965e938517eSTobias Grosser 
1966e938517eSTobias Grosser     Options->reschedule = true;
1967e938517eSTobias Grosser     Options->scale_tile_loops = false;
1968e938517eSTobias Grosser     Options->wrap = false;
1969e938517eSTobias Grosser 
1970e938517eSTobias Grosser     Options->non_negative_parameters = false;
1971e938517eSTobias Grosser     Options->ctx = nullptr;
1972e938517eSTobias Grosser     Options->sizes = nullptr;
1973e938517eSTobias Grosser 
19744eaedde5STobias Grosser     Options->tile_size = 32;
19754eaedde5STobias Grosser 
1976130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
1977b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1978b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1979e938517eSTobias Grosser 
1980e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1981e938517eSTobias Grosser     Options->openmp = false;
1982e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1983e938517eSTobias Grosser     Options->live_range_reordering = false;
1984e938517eSTobias Grosser 
1985e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1986e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1987e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1988e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1989e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1990e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1991e938517eSTobias Grosser 
1992e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1993e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1994e938517eSTobias Grosser 
1995e938517eSTobias Grosser     return Options;
1996e938517eSTobias Grosser   }
1997e938517eSTobias Grosser 
1998f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1999f384594dSTobias Grosser   ///
2000f384594dSTobias Grosser   /// Instead of a normal access of the form:
2001f384594dSTobias Grosser   ///
2002f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2003f384594dSTobias Grosser   ///
2004f384594dSTobias Grosser   /// a tagged access has the form
2005f384594dSTobias Grosser   ///
2006f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2007f384594dSTobias Grosser   ///
2008f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2009f384594dSTobias Grosser   /// triggered the access.
2010f384594dSTobias Grosser   ///
2011f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2012f384594dSTobias Grosser   ///
2013f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2014f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2015f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2016f384594dSTobias Grosser 
2017f384594dSTobias Grosser     for (auto &Stmt : *S)
2018f384594dSTobias Grosser       for (auto &Acc : Stmt)
2019f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
2020f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
2021f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2022f384594dSTobias Grosser 
2023f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2024f384594dSTobias Grosser           Space = isl_space_range(Space);
2025f384594dSTobias Grosser           Space = isl_space_from_range(Space);
20266293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2027f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2028f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2029f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2030f384594dSTobias Grosser         }
2031f384594dSTobias Grosser 
2032f384594dSTobias Grosser     return Accesses;
2033f384594dSTobias Grosser   }
2034f384594dSTobias Grosser 
2035f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2036f384594dSTobias Grosser   ///
2037f384594dSTobias Grosser   /// @see getTaggedAccesses
2038f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2039f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2040f384594dSTobias Grosser   }
2041f384594dSTobias Grosser 
2042f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2043f384594dSTobias Grosser   ///
2044f384594dSTobias Grosser   /// @see getTaggedAccesses
2045f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2046f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2047f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2048f384594dSTobias Grosser   }
2049f384594dSTobias Grosser 
2050f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2051f384594dSTobias Grosser   ///
2052f384594dSTobias Grosser   /// @see getTaggedAccesses
2053f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2054f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2055f384594dSTobias Grosser   }
2056f384594dSTobias Grosser 
2057aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2058aef5196fSTobias Grosser   ///
2059aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2060aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2061aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2062aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2063aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2064aef5196fSTobias Grosser   /// the data format that ppcg expects.
2065aef5196fSTobias Grosser   ///
2066aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2067aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2068aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2069bd81a7eeSTobias Grosser         S->getIslCtx(),
2070bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2071aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2072aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
2073aef5196fSTobias Grosser 
2074aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2075aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2076aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2077aef5196fSTobias Grosser     }
2078aef5196fSTobias Grosser 
2079aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
2080d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
2081aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2082aef5196fSTobias Grosser     }
2083aef5196fSTobias Grosser 
2084aef5196fSTobias Grosser     isl_space_free(Space);
2085aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2086aef5196fSTobias Grosser 
2087aef5196fSTobias Grosser     return Names;
2088aef5196fSTobias Grosser   }
2089aef5196fSTobias Grosser 
2090e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2091e938517eSTobias Grosser   ///
2092f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2093f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2094f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2095f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2096e938517eSTobias Grosser   ///
2097e938517eSTobias Grosser   /// @returns A new ppcg scop.
2098e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
2099e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2100e938517eSTobias Grosser 
2101e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2102e938517eSTobias Grosser 
2103e938517eSTobias Grosser     PPCGScop->start = 0;
2104e938517eSTobias Grosser     PPCGScop->end = 0;
2105e938517eSTobias Grosser 
2106f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2107f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
2108e938517eSTobias Grosser     PPCGScop->call = nullptr;
2109f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2110f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2111e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2112f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2113f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2114f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2115f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2116e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
2117f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
2118e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2119e938517eSTobias Grosser 
2120e938517eSTobias Grosser     PPCGScop->independence = nullptr;
2121e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2122e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2123e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2124e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2125e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2126e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2127e938517eSTobias Grosser 
2128f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2129aef5196fSTobias Grosser     PPCGScop->names = getNames();
2130e938517eSTobias Grosser 
2131e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2132e938517eSTobias Grosser 
2133f384594dSTobias Grosser     compute_tagger(PPCGScop);
2134f384594dSTobias Grosser     compute_dependences(PPCGScop);
2135f384594dSTobias Grosser 
2136e938517eSTobias Grosser     return PPCGScop;
2137e938517eSTobias Grosser   }
2138e938517eSTobias Grosser 
2139a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
214060f63b49STobias Grosser   ///
214160f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
214260f63b49STobias Grosser   ///
214360f63b49STobias Grosser   /// @returns A list of array accesses.
214460f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
214560f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
214660f63b49STobias Grosser 
214760f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
214860f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
214960f63b49STobias Grosser       Access->read = Acc->isRead();
215060f63b49STobias Grosser       Access->write = Acc->isWrite();
215160f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
215260f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
215360f63b49STobias Grosser       Space = isl_space_range(Space);
215460f63b49STobias Grosser       Space = isl_space_from_range(Space);
21556293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
215660f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
215760f63b49STobias Grosser       Access->tagged_access =
215860f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2159b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
216060f63b49STobias Grosser       Access->ref_id = Acc->getId();
216160f63b49STobias Grosser       Access->next = Accesses;
2162b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
216360f63b49STobias Grosser       Accesses = Access;
216460f63b49STobias Grosser     }
216560f63b49STobias Grosser 
216660f63b49STobias Grosser     return Accesses;
216760f63b49STobias Grosser   }
216860f63b49STobias Grosser 
216969b46751STobias Grosser   /// Collect the list of GPU statements.
217069b46751STobias Grosser   ///
217169b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
217269b46751STobias Grosser   /// as well as a list with all memory accesses.
217369b46751STobias Grosser   ///
217469b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
217569b46751STobias Grosser   ///
217669b46751STobias Grosser   /// @returns A linked-list of statements.
217769b46751STobias Grosser   gpu_stmt *getStatements() {
217869b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
217969b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
218069b46751STobias Grosser 
218169b46751STobias Grosser     int i = 0;
218269b46751STobias Grosser     for (auto &Stmt : *S) {
218369b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
218469b46751STobias Grosser 
218569b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
218669b46751STobias Grosser 
218769b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
218869b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
218960f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
219069b46751STobias Grosser       i++;
219169b46751STobias Grosser     }
219269b46751STobias Grosser 
219369b46751STobias Grosser     return Stmts;
219469b46751STobias Grosser   }
219569b46751STobias Grosser 
219660f63b49STobias Grosser   /// Derive the extent of an array.
219760f63b49STobias Grosser   ///
2198d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2199d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2200d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2201d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2202d58acf86STobias Grosser   /// subscript value for the first dimension.
220360f63b49STobias Grosser   ///
220460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
220560f63b49STobias Grosser   ///
220660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
220760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2208d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
220960f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
221060f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2211d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
221260f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2213d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2214d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2215d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2216d58acf86STobias Grosser 
2217d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2218d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2219d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2220d58acf86STobias Grosser     }
2221d58acf86STobias Grosser 
2222d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2223d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2224d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2225d58acf86STobias Grosser     }
2226d58acf86STobias Grosser 
222760f63b49STobias Grosser     isl_set *AccessSet =
222860f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
222960f63b49STobias Grosser 
2230d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2231d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2232d58acf86STobias Grosser 
2233d58acf86STobias Grosser     isl_pw_aff *Val =
2234d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2235d58acf86STobias Grosser 
2236d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2237d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2238d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2239d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2240d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2241d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2242d58acf86STobias Grosser     OuterMin =
2243d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2244d58acf86STobias Grosser     OuterMax =
2245d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2246d58acf86STobias Grosser 
2247d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2248d58acf86STobias Grosser 
2249d58acf86STobias Grosser     Extent = isl_set_intersect(
2250d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2251d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2252d58acf86STobias Grosser 
2253d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2254d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2255d58acf86STobias Grosser 
2256b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2257d58acf86STobias Grosser       isl_pw_aff *PwAff =
2258d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2259b7f68b8cSSiddharth Bhat 
2260b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2261b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2262b7f68b8cSSiddharth Bhat       if (!PwAff) {
2263b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2264b7f68b8cSSiddharth Bhat         continue;
2265b7f68b8cSSiddharth Bhat       }
2266b7f68b8cSSiddharth Bhat 
2267d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2268d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2269d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2270d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2271d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2272d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2273d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2274d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2275d58acf86STobias Grosser     }
2276d58acf86STobias Grosser 
2277d58acf86STobias Grosser     return Extent;
227860f63b49STobias Grosser   }
227960f63b49STobias Grosser 
228060f63b49STobias Grosser   /// Derive the bounds of an array.
228160f63b49STobias Grosser   ///
228260f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
228360f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
228460f63b49STobias Grosser   /// ScopArrayInfo.
228560f63b49STobias Grosser   ///
228660f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
228760f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
228860f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
228960f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
229002293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
229102293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
229202293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
229302293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
229402293ed7STobias Grosser         isl_set_free(Dom);
229502293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
229602293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
229702293ed7STobias Grosser       } else {
229860f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
229960f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
230060f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
230160f63b49STobias Grosser         isl_set_free(Dom);
230260f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
230302293ed7STobias Grosser         isl_local_space *LS =
230402293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
230560f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
230660f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
230760f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
230860f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
230960f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
231060f63b49STobias Grosser       }
231102293ed7STobias Grosser     }
231260f63b49STobias Grosser 
231360f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
231460f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
231560f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
231660f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
231760f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
231860f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
231960f63b49STobias Grosser     }
232060f63b49STobias Grosser   }
232160f63b49STobias Grosser 
232260f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
232360f63b49STobias Grosser   ///
232460f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
232560f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
232660f63b49STobias Grosser     int i = 0;
2327d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
232860f63b49STobias Grosser       std::string TypeName;
232960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
233060f63b49STobias Grosser 
233160f63b49STobias Grosser       OS << *Array->getElementType();
233260f63b49STobias Grosser       TypeName = OS.str();
233360f63b49STobias Grosser 
233460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
233560f63b49STobias Grosser 
233660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
233760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
233860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
233960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
234060f63b49STobias Grosser       PPCGArray.extent = nullptr;
234160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
234260f63b49STobias Grosser       PPCGArray.bound =
234360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
234460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
234560f63b49STobias Grosser       PPCGArray.n_ref = 0;
234660f63b49STobias Grosser       PPCGArray.refs = nullptr;
234760f63b49STobias Grosser       PPCGArray.accessed = true;
2348fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2349fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
235060f63b49STobias Grosser       PPCGArray.has_compound_element = false;
235160f63b49STobias Grosser       PPCGArray.local = false;
235260f63b49STobias Grosser       PPCGArray.declare_local = false;
235360f63b49STobias Grosser       PPCGArray.global = false;
235460f63b49STobias Grosser       PPCGArray.linearize = false;
235560f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
235613c78e4dSTobias Grosser       PPCGArray.user = Array;
235760f63b49STobias Grosser 
235860f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
23592d010dafSTobias Grosser       i++;
2360b9fc860aSTobias Grosser 
2361b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
236260f63b49STobias Grosser     }
236360f63b49STobias Grosser   }
236460f63b49STobias Grosser 
236560f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
236660f63b49STobias Grosser   ///
236760f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
236860f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
236960f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
237060f63b49STobias Grosser 
2371d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
237260f63b49STobias Grosser       isl_space *Space = Array->getSpace();
237360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
237460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
237560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
237660f63b49STobias Grosser     }
237760f63b49STobias Grosser 
237860f63b49STobias Grosser     return Maps;
237960f63b49STobias Grosser   }
238060f63b49STobias Grosser 
2381e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2382e938517eSTobias Grosser   ///
2383a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2384e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2385e938517eSTobias Grosser 
2386e938517eSTobias Grosser     if (!PPCGScop)
2387e938517eSTobias Grosser       return nullptr;
2388e938517eSTobias Grosser 
2389e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2390e938517eSTobias Grosser 
2391e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2392e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2393aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
239460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
239560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
239660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
239760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
239860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
239960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
240060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2401e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2402e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
240369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
240469b46751STobias Grosser     PPCGProg->stmts = getStatements();
240560f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
240660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
240760f63b49STobias Grosser                                        PPCGProg->n_array);
240860f63b49STobias Grosser 
240960f63b49STobias Grosser     createArrays(PPCGProg);
2410e938517eSTobias Grosser 
2411d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2412d58acf86STobias Grosser 
2413e938517eSTobias Grosser     return PPCGProg;
2414e938517eSTobias Grosser   }
2415e938517eSTobias Grosser 
241669b46751STobias Grosser   struct PrintGPUUserData {
241769b46751STobias Grosser     struct cuda_info *CudaInfo;
241869b46751STobias Grosser     struct gpu_prog *PPCGProg;
241969b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
242069b46751STobias Grosser   };
242169b46751STobias Grosser 
242269b46751STobias Grosser   /// Print a user statement node in the host code.
242369b46751STobias Grosser   ///
242469b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
242569b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
242669b46751STobias Grosser   /// host ast.
242769b46751STobias Grosser   ///
242869b46751STobias Grosser   /// @param P The printer to print to
242969b46751STobias Grosser   /// @param Options The printing options to use
243069b46751STobias Grosser   /// @param Node The node to print
243169b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
243269b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
243369b46751STobias Grosser   ///
243469b46751STobias Grosser   /// @returns A printer to which the output has been printed.
243569b46751STobias Grosser   static __isl_give isl_printer *
243669b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
243769b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
243869b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
243969b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
244069b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
244169b46751STobias Grosser 
244269b46751STobias Grosser     if (Id) {
244320251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
244420251734STobias Grosser 
244520251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
244620251734STobias Grosser       // otherwise try to call pet functionality that is not available in
244720251734STobias Grosser       // Polly.
244820251734STobias Grosser       if (IsUser) {
244920251734STobias Grosser         P = isl_printer_start_line(P);
245020251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
245120251734STobias Grosser         P = isl_printer_end_line(P);
245220251734STobias Grosser         isl_id_free(Id);
245320251734STobias Grosser         isl_ast_print_options_free(Options);
245420251734STobias Grosser         return P;
245520251734STobias Grosser       }
245620251734STobias Grosser 
245769b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
245869b46751STobias Grosser       isl_id_free(Id);
245969b46751STobias Grosser       Data->Kernels.push_back(Kernel);
246069b46751STobias Grosser     }
246169b46751STobias Grosser 
246269b46751STobias Grosser     return print_host_user(P, Options, Node, User);
246369b46751STobias Grosser   }
246469b46751STobias Grosser 
246569b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
246669b46751STobias Grosser   ///
246769b46751STobias Grosser   /// @param Kernel The kernel to print
246869b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
246969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
247069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
247169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
247269b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
247369b46751STobias Grosser     char *String = isl_printer_get_str(P);
247469b46751STobias Grosser     printf("%s\n", String);
247569b46751STobias Grosser     free(String);
247669b46751STobias Grosser     isl_printer_free(P);
247769b46751STobias Grosser   }
247869b46751STobias Grosser 
247969b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
248069b46751STobias Grosser   ///
248169b46751STobias Grosser   /// @param Tree An AST describing GPU code
248269b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
248369b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
248469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
248569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
248669b46751STobias Grosser 
248769b46751STobias Grosser     PrintGPUUserData Data;
248869b46751STobias Grosser     Data.PPCGProg = PPCGProg;
248969b46751STobias Grosser 
249069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
249169b46751STobias Grosser     Options =
249269b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
249369b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
249469b46751STobias Grosser     char *String = isl_printer_get_str(P);
249569b46751STobias Grosser     printf("# host\n");
249669b46751STobias Grosser     printf("%s\n", String);
249769b46751STobias Grosser     free(String);
249869b46751STobias Grosser     isl_printer_free(P);
249969b46751STobias Grosser 
250069b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
250169b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
250269b46751STobias Grosser       printKernel(Kernel);
250369b46751STobias Grosser     }
250469b46751STobias Grosser   }
250569b46751STobias Grosser 
2506f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2507f384594dSTobias Grosser   //
2508f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2509f384594dSTobias Grosser   //
2510f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2511f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2512f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2513f384594dSTobias Grosser   //
2514f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2515f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2516f384594dSTobias Grosser   // strategy directly from this pass.
2517f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2518f384594dSTobias Grosser 
2519f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2520f384594dSTobias Grosser 
2521f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2522f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2523f384594dSTobias Grosser     PPCGGen->print = nullptr;
2524f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
252560c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2526f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2527f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2528f384594dSTobias Grosser     PPCGGen->types.n = 0;
2529f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2530f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2531f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2532f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2533f384594dSTobias Grosser 
2534f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2535f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2536f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
25372341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2538f384594dSTobias Grosser 
2539f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2540f384594dSTobias Grosser 
2541aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2542aef5196fSTobias Grosser 
254369b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2544aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
254569b46751STobias Grosser     } else {
2546aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
254769b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
254869b46751STobias Grosser     }
2549aef5196fSTobias Grosser 
2550f384594dSTobias Grosser     if (DumpSchedule) {
2551f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2552f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2553f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2554f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2555f384594dSTobias Grosser       if (Schedule)
2556f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2557f384594dSTobias Grosser       else
2558f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2559f384594dSTobias Grosser 
2560f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2561f384594dSTobias Grosser       isl_printer_free(P);
2562f384594dSTobias Grosser     }
2563f384594dSTobias Grosser 
256469b46751STobias Grosser     if (DumpCode) {
256569b46751STobias Grosser       printf("Code\n");
256669b46751STobias Grosser       printf("====\n");
256769b46751STobias Grosser       if (PPCGGen->tree)
256869b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
256969b46751STobias Grosser       else
257069b46751STobias Grosser         printf("No code generated\n");
257169b46751STobias Grosser     }
257269b46751STobias Grosser 
2573f384594dSTobias Grosser     isl_schedule_free(Schedule);
2574f384594dSTobias Grosser 
2575f384594dSTobias Grosser     return PPCGGen;
2576f384594dSTobias Grosser   }
2577f384594dSTobias Grosser 
2578f384594dSTobias Grosser   /// Free gpu_gen structure.
2579f384594dSTobias Grosser   ///
2580f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2581f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2582f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2583f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2584f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2585f384594dSTobias Grosser     free(PPCGGen);
2586f384594dSTobias Grosser   }
2587f384594dSTobias Grosser 
2588b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2589b307ed4dSTobias Grosser   ///
2590b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2591b307ed4dSTobias Grosser   /// ourselves.
2592b307ed4dSTobias Grosser   ///
2593b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2594b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2595b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2596b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2597b307ed4dSTobias Grosser     free(PPCGScop->options);
2598b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2599b307ed4dSTobias Grosser   }
2600b307ed4dSTobias Grosser 
260182f2af35STobias Grosser   /// Approximate the number of points in the set.
260282f2af35STobias Grosser   ///
260382f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
260482f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
260582f2af35STobias Grosser   ///
260682f2af35STobias Grosser   /// @param Set   The set to count.
260782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
260882f2af35STobias Grosser   ///              expression.
260982f2af35STobias Grosser   ///
261082f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
261182f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
261282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
261382f2af35STobias Grosser 
261482f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
261582f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
261682f2af35STobias Grosser 
261782f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
261882f2af35STobias Grosser     Space = isl_space_params(Space);
261982f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
262082f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
262182f2af35STobias Grosser 
262282f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
262382f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
262482f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
262582f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
262682f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
262782f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
262882f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
262982f2af35STobias Grosser     }
263082f2af35STobias Grosser 
263182f2af35STobias Grosser     isl_set_free(Set);
263282f2af35STobias Grosser     isl_pw_aff_free(OneAff);
263382f2af35STobias Grosser 
263482f2af35STobias Grosser     return Expr;
263582f2af35STobias Grosser   }
263682f2af35STobias Grosser 
263782f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
263882f2af35STobias Grosser   /// statement.
263982f2af35STobias Grosser   ///
264082f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
264182f2af35STobias Grosser   ///              instructions.
264282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
264382f2af35STobias Grosser   ///              expression.
264482f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
264582f2af35STobias Grosser   ///          by @p Stmt.
264682f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
264782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
264882f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
264982f2af35STobias Grosser 
265082f2af35STobias Grosser     long InstCount = 0;
265182f2af35STobias Grosser 
265282f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
265382f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
265482f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
265582f2af35STobias Grosser     } else {
265682f2af35STobias Grosser       auto *R = Stmt.getRegion();
265782f2af35STobias Grosser 
265882f2af35STobias Grosser       for (auto *BB : R->blocks()) {
265982f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
266082f2af35STobias Grosser       }
266182f2af35STobias Grosser     }
266282f2af35STobias Grosser 
266382f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
266482f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
266582f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
266682f2af35STobias Grosser   }
266782f2af35STobias Grosser 
266882f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
266982f2af35STobias Grosser   ///
267082f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
267182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
267282f2af35STobias Grosser   ///              expression.
267382f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
267482f2af35STobias Grosser   ///          in @p S.
267582f2af35STobias Grosser   __isl_give isl_ast_expr *
267682f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
267782f2af35STobias Grosser     isl_ast_expr *Instructions;
267882f2af35STobias Grosser 
267982f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
268082f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
268182f2af35STobias Grosser 
268282f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
268382f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
268482f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
268582f2af35STobias Grosser     }
268682f2af35STobias Grosser     return Instructions;
268782f2af35STobias Grosser   }
268882f2af35STobias Grosser 
268982f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
269082f2af35STobias Grosser   ///
269182f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
269282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
269382f2af35STobias Grosser   ///              expression.
269482f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
269582f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
269682f2af35STobias Grosser   __isl_give isl_ast_expr *
269782f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
269882f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
269982f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
270082f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
270182f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
270282f2af35STobias Grosser   }
270382f2af35STobias Grosser 
2704*f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
2705*f291c8d5SSiddharth Bhat   /// kernels.
2706*f291c8d5SSiddharth Bhat   ///
2707*f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
2708*f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
2709*f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) {
2710*f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
2711*f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2712*f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2713*f291c8d5SSiddharth Bhat         continue;
2714*f291c8d5SSiddharth Bhat       }
2715*f291c8d5SSiddharth Bhat 
2716bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
2717bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2718bccaea57SSiddharth Bhat         if (!p)
2719bccaea57SSiddharth Bhat           continue;
2720bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
2721bccaea57SSiddharth Bhat           return true;
2722bccaea57SSiddharth Bhat       }
2723*f291c8d5SSiddharth Bhat     }
2724bccaea57SSiddharth Bhat     return false;
2725bccaea57SSiddharth Bhat   }
2726bccaea57SSiddharth Bhat 
2727*f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
2728*f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
2729bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
2730bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
2731*f291c8d5SSiddharth Bhat         if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock()))
2732bccaea57SSiddharth Bhat           return true;
2733bccaea57SSiddharth Bhat       } else {
2734bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
2735bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
2736bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2737*f291c8d5SSiddharth Bhat           if (containsInvalidKernelFunctionInBllock(BB))
2738bccaea57SSiddharth Bhat             return true;
2739bccaea57SSiddharth Bhat       }
2740bccaea57SSiddharth Bhat     }
2741bccaea57SSiddharth Bhat     return false;
2742bccaea57SSiddharth Bhat   }
2743bccaea57SSiddharth Bhat 
274438fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
274538fc0aedSTobias Grosser   ///
274632837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
274732837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
274832837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
274938fc0aedSTobias Grosser     ScopAnnotator Annotator;
275038fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
275138fc0aedSTobias Grosser 
275238fc0aedSTobias Grosser     Region *R = &S->getRegion();
275338fc0aedSTobias Grosser 
275438fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
275538fc0aedSTobias Grosser 
275638fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
275738fc0aedSTobias Grosser 
275838fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
275938fc0aedSTobias Grosser 
276038fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
276138fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
276238fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
276338fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
276438fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
276538fc0aedSTobias Grosser     // code generating this scop.
2766256070d8SAndreas Simbuerger     BBPair StartExitBlocks =
27672d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
2768256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
276938fc0aedSTobias Grosser 
27702d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
277117f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
2772acf80064SEli Friedman 
277338fc0aedSTobias Grosser     // TODO: Handle LICM
277438fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
277538fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
277638fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2777cb1aef8dSTobias Grosser 
2778cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
27792b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
278082f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
278182f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2782cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2783cb1aef8dSTobias Grosser 
2784cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2785cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2786cb1aef8dSTobias Grosser 
278738fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2788fa7b0802STobias Grosser 
2789fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
279038fc0aedSTobias Grosser     NodeBuilder.create(Root);
27918ed5e599STobias Grosser     NodeBuilder.finalize();
27925857b701STobias Grosser 
2793bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
2794bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2795de244eb4STobias Grosser     /// point in running it on a GPU.
2796bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2797bc653f20STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2798bc653f20STobias Grosser 
27995857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
28005857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
280138fc0aedSTobias Grosser   }
280238fc0aedSTobias Grosser 
2803e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2804e938517eSTobias Grosser     S = &CurrentScop;
280538fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
280638fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
280738fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
28087b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
280938fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2810e938517eSTobias Grosser 
2811*f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
2812*f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
2813*f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
2814bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
2815bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
2816*f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
2817*f291c8d5SSiddharth Bhat       DEBUG(
2818*f291c8d5SSiddharth Bhat           dbgs()
2819*f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
2820*f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
2821bccaea57SSiddharth Bhat       return false;
2822*f291c8d5SSiddharth Bhat     }
2823bccaea57SSiddharth Bhat 
2824e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2825e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2826f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
282738fc0aedSTobias Grosser 
282838fc0aedSTobias Grosser     if (PPCGGen->tree)
282932837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
283038fc0aedSTobias Grosser 
2831b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2832f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2833e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2834e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2835e938517eSTobias Grosser 
2836e938517eSTobias Grosser     return true;
2837e938517eSTobias Grosser   }
28389dfe4e7cSTobias Grosser 
28399dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
28409dfe4e7cSTobias Grosser 
28419dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
28429dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
28439dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
28449dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
28455cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
28469dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
28479dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
28489dfe4e7cSTobias Grosser 
28499dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
28509dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
28519dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
28529dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
28539dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
28545cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
28559dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
28569dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
28579dfe4e7cSTobias Grosser 
28589dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
28599dfe4e7cSTobias Grosser     //        region tree.
28609dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
28619dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
28629dfe4e7cSTobias Grosser   }
28639dfe4e7cSTobias Grosser };
286424222c73STobias Grosser } // namespace
28659dfe4e7cSTobias Grosser 
28669dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
28679dfe4e7cSTobias Grosser 
286817f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
286917f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
287017f01968SSiddharth Bhat   generator->Runtime = Runtime;
287117f01968SSiddharth Bhat   generator->Architecture = Arch;
287217f01968SSiddharth Bhat   return generator;
287317f01968SSiddharth Bhat }
28749dfe4e7cSTobias Grosser 
28759dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
28769dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
28779dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
28789dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
28799dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
28809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
28819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
28825cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
28839dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
28849dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2885