19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69dfe4e7cSTobias Grosser //
79dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
89dfe4e7cSTobias Grosser //
99dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
109dfe4e7cSTobias Grosser // GPU mapping strategy.
119dfe4e7cSTobias Grosser //
129dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
139dfe4e7cSTobias Grosser 
1417f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
1571dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
187b9f5ca2SSiddharth Bhat #include "polly/CodeGen/PerfMonitor.h"
1938fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
209dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
219dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
22f384594dSTobias Grosser #include "polly/Options.h"
23629109b6STobias Grosser #include "polly/ScopDetection.h"
249dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
2544596fe6SRiccardo Mori #include "polly/Support/ISLTools.h"
26edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2774dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
2874dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
290133dc39SHeejin Ahn #include "llvm/IR/IntrinsicsNVPTX.h"
3074dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
31e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
328fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
332c831971SMichael Kruse #include "llvm/InitializePasses.h"
348fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
3589b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
36031bb165SMichael Kruse #include "llvm/Support/SourceMgr.h"
3774dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
389a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40f384594dSTobias Grosser #include "isl/union_map.h"
41e8227804SMichael Kruse #include <algorithm>
42f384594dSTobias Grosser 
43e938517eSTobias Grosser extern "C" {
44a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47e938517eSTobias Grosser }
48e938517eSTobias Grosser 
499dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
509dfe4e7cSTobias Grosser 
519dfe4e7cSTobias Grosser using namespace polly;
529dfe4e7cSTobias Grosser using namespace llvm;
539dfe4e7cSTobias Grosser 
549dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
559dfe4e7cSTobias Grosser 
56f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
57f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
58*36c7d79dSFangrui Song                                   cl::Hidden, cl::cat(PollyCategory));
5969b46751STobias Grosser 
6069b46751STobias Grosser static cl::opt<bool>
6169b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6269b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
63*36c7d79dSFangrui Song              cl::cat(PollyCategory));
6469b46751STobias Grosser 
6532837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6632837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
67*36c7d79dSFangrui Song                                   cl::Hidden, cl::cat(PollyCategory));
6832837fe3STobias Grosser 
6974dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7074dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
71*36c7d79dSFangrui Song                                    cl::Hidden, cl::cat(PollyCategory));
7274dc3cb4STobias Grosser 
7374dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7474dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
75*36c7d79dSFangrui Song                               cl::Hidden, cl::cat(PollyCategory));
76b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
77b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
78b513b491STobias Grosser                                   cl::cat(PollyCategory));
79130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
80130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
81130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8274dc3cb4STobias Grosser 
83c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory;
84c4a4af47SSiddharth Bhat static cl::opt<bool, true>
85c4a4af47SSiddharth Bhat     XManagedMemory("polly-acc-codegen-managed-memory",
86abed4969SSiddharth Bhat                    cl::desc("Generate Host kernel code assuming"
87abed4969SSiddharth Bhat                             " that all memory has been"
88abed4969SSiddharth Bhat                             " declared as managed memory"),
89c4a4af47SSiddharth Bhat                    cl::location(PollyManagedMemory), cl::Hidden,
90c4a4af47SSiddharth Bhat                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
91abed4969SSiddharth Bhat 
9265d7f72fSSiddharth Bhat static cl::opt<bool>
9365d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
9465d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
9565d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
9665d7f72fSSiddharth Bhat                                        " kernel module."),
9765d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
9865d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
9965d7f72fSSiddharth Bhat 
1008fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1018fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1028fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1038fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1048fc6cdfbSTobias Grosser 
10574dc3cb4STobias Grosser static cl::opt<std::string>
10674dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
10774dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
108*36c7d79dSFangrui Song                 cl::init("sm_30"), cl::cat(PollyCategory));
10974dc3cb4STobias Grosser 
11082f2af35STobias Grosser static cl::opt<int>
11182f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11282f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
11382f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
11482f2af35STobias Grosser 
1153dcb5351SMichael Kruse GPURuntime polly::GPURuntimeChoice;
1163dcb5351SMichael Kruse static cl::opt<GPURuntime, true> XGPURuntimeChoice(
1173dcb5351SMichael Kruse     "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"),
1183dcb5351SMichael Kruse     cl::values(clEnumValN(GPURuntime::CUDA, "libcudart",
1193dcb5351SMichael Kruse                           "use the CUDA Runtime API"),
1203dcb5351SMichael Kruse                clEnumValN(GPURuntime::OpenCL, "libopencl",
1213dcb5351SMichael Kruse                           "use the OpenCL Runtime API")),
1223dcb5351SMichael Kruse     cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA),
1233dcb5351SMichael Kruse     cl::ZeroOrMore, cl::cat(PollyCategory));
1243dcb5351SMichael Kruse 
1253dcb5351SMichael Kruse GPUArch polly::GPUArchChoice;
1263dcb5351SMichael Kruse static cl::opt<GPUArch, true>
1273dcb5351SMichael Kruse     XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"),
1283dcb5351SMichael Kruse                    cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64",
1293dcb5351SMichael Kruse                                          "target NVIDIA 64-bit architecture"),
1303dcb5351SMichael Kruse                               clEnumValN(GPUArch::SPIR32, "spir32",
1313dcb5351SMichael Kruse                                          "target SPIR 32-bit architecture"),
1323dcb5351SMichael Kruse                               clEnumValN(GPUArch::SPIR64, "spir64",
1333dcb5351SMichael Kruse                                          "target SPIR 64-bit architecture")),
1343dcb5351SMichael Kruse                    cl::location(polly::GPUArchChoice),
1353dcb5351SMichael Kruse                    cl::init(GPUArch::NVPTX64), cl::ZeroOrMore,
1363dcb5351SMichael Kruse                    cl::cat(PollyCategory));
1373dcb5351SMichael Kruse 
1387b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring;
1397b9f5ca2SSiddharth Bhat 
140638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
141638316daSSiddharth Bhat /// function name.
142638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
143638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
144638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
145638316daSSiddharth Bhat }
146638316daSSiddharth Bhat 
147a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
148a82f2d26SSiddharth Bhat /// used by live range reordering.
149a82f2d26SSiddharth Bhat ///
150a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
151a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
152a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
153a82f2d26SSiddharth Bhat struct MustKillsInfo {
154a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
155a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
156a82f2d26SSiddharth Bhat   ///
157a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
158a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
159a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
160a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
161a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
162a82f2d26SSiddharth Bhat   /// killed.
163a82f2d26SSiddharth Bhat   ///
164edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
165edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
166edfef5aeSSiddharth Bhat   ///     consequently all be killed.
167edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
168edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
169edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
170a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
171a82f2d26SSiddharth Bhat 
1729e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1739e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1749e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1759e3db2b7SSiddharth Bhat 
1769b41d095Spatacca   MustKillsInfo() : KillsSchedule() {}
177a82f2d26SSiddharth Bhat };
178a82f2d26SSiddharth Bhat 
179761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
180761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
181761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
182761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
183761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
184761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
185761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
186761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
187761e5b93SSiddharth Bhat 
188761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
189761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
190761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
191761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
192761e5b93SSiddharth Bhat     if (!R.contains(I))
193761e5b93SSiddharth Bhat       return false;
194761e5b93SSiddharth Bhat   }
195761e5b93SSiddharth Bhat   return true;
196761e5b93SSiddharth Bhat }
197761e5b93SSiddharth Bhat 
198a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
199a82f2d26SSiddharth Bhat ///
200a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
201a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
202a82f2d26SSiddharth Bhat /// PPCG.
203a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
204b65ccc43STobias Grosser   const isl::space ParamSpace = S.getParamSpace();
205a82f2d26SSiddharth Bhat   MustKillsInfo Info;
206a82f2d26SSiddharth Bhat 
207761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
208761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
209761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
210a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
211a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
212761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
213761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
21477eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
215a82f2d26SSiddharth Bhat   }
216a82f2d26SSiddharth Bhat 
217bad3ebbaSRiccardo Mori   Info.TaggedMustKills = isl::union_map::empty(ParamSpace.ctx());
218bad3ebbaSRiccardo Mori   Info.MustKills = isl::union_map::empty(ParamSpace.ctx());
219a82f2d26SSiddharth Bhat 
220a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
221a82f2d26SSiddharth Bhat   // schedule:
222a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
223a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
224a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
2259b41d095Spatacca   Info.KillsSchedule = {};
226a82f2d26SSiddharth Bhat 
227edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
228a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
229edfef5aeSSiddharth Bhat         S.getIslCtx(),
230edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
231a82f2d26SSiddharth Bhat 
232a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
233a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
234edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
235a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
236edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
237edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
238edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
239edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
240a82f2d26SSiddharth Bhat     //
241a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
242a82f2d26SSiddharth Bhat     // TaggedMustKill:
243edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
244a82f2d26SSiddharth Bhat 
245edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
246d70ea7feSTobias Grosser     isl::map StmtToScalar = isl::map::universe(ParamSpace);
247edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
248edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
249a82f2d26SSiddharth Bhat 
250a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
251edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
252edfef5aeSSiddharth Bhat         nullptr);
253a82f2d26SSiddharth Bhat 
254edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
255d70ea7feSTobias Grosser     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
256edfef5aeSSiddharth Bhat     PhantomRefToScalar =
257edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
258edfef5aeSSiddharth Bhat     PhantomRefToScalar =
259edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
260a82f2d26SSiddharth Bhat 
261edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
262edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
263a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
264a82f2d26SSiddharth Bhat 
2659e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2669e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2679e3db2b7SSiddharth Bhat 
268a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
269a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
270a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
271a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
272a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
273a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
274a82f2d26SSiddharth Bhat 
275a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
2767c7978a1Spatacca     if (!Info.KillsSchedule.is_null())
2775f865032STobias Grosser       Info.KillsSchedule = isl::manage(
2785f865032STobias Grosser           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
279a82f2d26SSiddharth Bhat     else
280a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
281a82f2d26SSiddharth Bhat   }
282a82f2d26SSiddharth Bhat 
283a82f2d26SSiddharth Bhat   return Info;
284a82f2d26SSiddharth Bhat }
285a82f2d26SSiddharth Bhat 
28660c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
28760c60025STobias Grosser ///
28860c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
28960c60025STobias Grosser /// of the scheduled ScopStmts.
29060c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
29135de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
29260c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
29360c60025STobias Grosser                                        isl_id *Id, void *User),
29460c60025STobias Grosser     void *UserIndex,
29560c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
296edb885cbSTobias Grosser     void *UserExpr) {
29760c60025STobias Grosser 
298edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
29960c60025STobias Grosser 
30035de9009SSiddharth Bhat   if (!Stmt || !Build_C)
301edb885cbSTobias Grosser     return NULL;
302edb885cbSTobias Grosser 
303718d04c6STobias Grosser   isl::ast_build Build = isl::manage_copy(Build_C);
3040813bd16SRiccardo Mori   isl::ctx Ctx = Build.ctx();
30535de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
306edb885cbSTobias Grosser 
307cff9696eSTobias Grosser   Stmt->setAstBuild(Build);
308cff9696eSTobias Grosser 
309edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
31035de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
311dcf8d696STobias Grosser     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
31235de9009SSiddharth Bhat 
31335de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
31435de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
31535de9009SSiddharth Bhat 
31635de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
31735de9009SSiddharth Bhat     MPA = MPA.coalesce();
31835de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
31935de9009SSiddharth Bhat 
32035de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
32135de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
32235de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
323edb885cbSTobias Grosser   }
324edb885cbSTobias Grosser 
32535de9009SSiddharth Bhat   return RefToExpr.release();
32660c60025STobias Grosser }
327f384594dSTobias Grosser 
328a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
329a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
330a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
331a90be207SSiddharth Bhat   if (bytes == 0)
332a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
333a90be207SSiddharth Bhat   return bytes;
334a90be207SSiddharth Bhat }
335a90be207SSiddharth Bhat 
33638fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
33738fc0aedSTobias Grosser ///
33838fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
339a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
34038fc0aedSTobias Grosser /// for generating GPU specific user nodes.
34138fc0aedSTobias Grosser ///
34238fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
343bd93df93SMichael Kruse class GPUNodeBuilder final : public IslNodeBuilder {
34438fc0aedSTobias Grosser public:
3452d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
34638fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
347acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
34817f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3492d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
35017f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
351edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
352edb885cbSTobias Grosser   }
35338fc0aedSTobias Grosser 
354fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
355fa7b0802STobias Grosser   void initializeAfterRTH();
356fa7b0802STobias Grosser 
357fa7b0802STobias Grosser   /// Finalize the generated scop.
35833ca0b0eSMichael Kruse   void finalize() override;
359fa7b0802STobias Grosser 
3605857b701STobias Grosser   /// Track if the full build process was successful.
3615857b701STobias Grosser   ///
3625857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3635857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3645857b701STobias Grosser   bool BuildSuccessful = true;
3655857b701STobias Grosser 
366bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
367bc653f20STobias Grosser   unsigned DeepestSequential = 0;
368bc653f20STobias Grosser 
369bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
370bc653f20STobias Grosser   unsigned DeepestParallel = 0;
371bc653f20STobias Grosser 
37279f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
37379f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
37479f13b9aSSingapuram Sanjay Srivallabh 
37538fc0aedSTobias Grosser private:
37674dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
37774dc3cb4STobias Grosser   ///
37874dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
37974dc3cb4STobias Grosser   /// more.
38074dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
38174dc3cb4STobias Grosser 
38213c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
38313c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3847287aeddSTobias Grosser 
385fa7b0802STobias Grosser   /// The current GPU context.
386fa7b0802STobias Grosser   Value *GPUContext;
387fa7b0802STobias Grosser 
388b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
389b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
390b513b491STobias Grosser 
39132837fe3STobias Grosser   /// A module containing GPU code.
39232837fe3STobias Grosser   ///
39332837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
39432837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
39532837fe3STobias Grosser 
39632837fe3STobias Grosser   /// The GPU program we generate code for.
39732837fe3STobias Grosser   gpu_prog *Prog;
39832837fe3STobias Grosser 
39917f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
40017f01968SSiddharth Bhat   GPURuntime Runtime;
40117f01968SSiddharth Bhat 
40217f01968SSiddharth Bhat   /// The GPU Architecture to target.
40317f01968SSiddharth Bhat   GPUArch Arch;
40417f01968SSiddharth Bhat 
405472f9654STobias Grosser   /// Class to free isl_ids.
406bd93df93SMichael Kruse   class IslIdDeleter final {
407472f9654STobias Grosser   public:
408472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
409472f9654STobias Grosser   };
410472f9654STobias Grosser 
411472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
412472f9654STobias Grosser   ///
413472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
414472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
415472f9654STobias Grosser 
416edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
417edb885cbSTobias Grosser 
41838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
41938fc0aedSTobias Grosser   ///
42038fc0aedSTobias Grosser   /// These AST nodes can be of type:
42138fc0aedSTobias Grosser   ///
42238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
42338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
42413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4255260c041STobias Grosser   ///   - In-kernel synchronization
4265260c041STobias Grosser   ///   - In-kernel memory copy statement
42738fc0aedSTobias Grosser   ///
4281fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
42933ca0b0eSMichael Kruse   void createUser(__isl_take isl_ast_node *UserStmt) override;
43032837fe3STobias Grosser 
43133ca0b0eSMichael Kruse   void createFor(__isl_take isl_ast_node *Node) override;
43253c80387SPhilip Pfaffe 
43313c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
43413c78e4dSTobias Grosser 
43513c78e4dSTobias Grosser   /// Create code for a data transfer statement
43613c78e4dSTobias Grosser   ///
43713c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
43813c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
43913c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
44013c78e4dSTobias Grosser                           enum DataDirection Direction);
44113c78e4dSTobias Grosser 
442edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
443edb885cbSTobias Grosser   ///
444edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
445edb885cbSTobias Grosser   ///
446e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
447e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
448e53c924bSSiddharth Bhat   ///            kernel
449e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
450e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
451e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
452e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
453e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
454e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
455e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
456e53c924bSSiddharth Bhat   ///            Scops]
45743df2020STobias Grosser   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
45843df2020STobias Grosser              isl::space>
459f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
460edb885cbSTobias Grosser 
46179a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
46279a947c2STobias Grosser   ///
46379a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
46479a947c2STobias Grosser   ///
46579a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
46679a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
46779a947c2STobias Grosser 
468b99c1171STobias Grosser   /// Get the managed array pointer for sending host pointers to the device.
469abed4969SSiddharth Bhat   /// \note
470abed4969SSiddharth Bhat   /// This is to be used only with managed memory
471b99c1171STobias Grosser   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
472abed4969SSiddharth Bhat 
47379a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
47479a947c2STobias Grosser   ///
47579a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
47679a947c2STobias Grosser   ///
47779a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
47879a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
47979a947c2STobias Grosser 
480a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
481a90be207SSiddharth Bhat   /// parameters.
482a90be207SSiddharth Bhat   ///
483ee6bd28fSNikita Popov   /// @param ArrayTy    Array type of \p Parameters.
484a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
485a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
486a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
487a90be207SSiddharth Bhat   ///                   parameter.
488ee6bd28fSNikita Popov   void insertStoreParameter(Type *ArrayTy, Instruction *Parameters,
489ee6bd28fSNikita Popov                             Instruction *Param, int Index);
490a90be207SSiddharth Bhat 
49179a947c2STobias Grosser   /// Create kernel launch parameters.
49279a947c2STobias Grosser   ///
49379a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
49479a947c2STobias Grosser   /// @param F             The kernel function that has been created.
49557693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
49679a947c2STobias Grosser   ///
49779a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
49879a947c2STobias Grosser   ///          values that are passed to the kernel.
49957693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
50057693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
50179a947c2STobias Grosser 
502b513b491STobias Grosser   /// Create declarations for kernel variable.
503b513b491STobias Grosser   ///
504b513b491STobias Grosser   /// This includes shared memory declarations.
505b513b491STobias Grosser   ///
506b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
507b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
508b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
509b513b491STobias Grosser 
510c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
511c1c6a2a6STobias Grosser   ///
512c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
513c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
514c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
515c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
516c1c6a2a6STobias Grosser   /// as specified here.
517c1c6a2a6STobias Grosser   ///
518c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
519c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
520c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
521c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
522c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
523c1c6a2a6STobias Grosser                           Value *BlockDimZ);
524c1c6a2a6STobias Grosser 
52532837fe3STobias Grosser   /// Create GPU kernel.
52632837fe3STobias Grosser   ///
52732837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
52832837fe3STobias Grosser   ///
52932837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
53032837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
53132837fe3STobias Grosser 
53213c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
53313c78e4dSTobias Grosser   ///
53413c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
53513c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
53613c78e4dSTobias Grosser 
537aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
538aaabbbf8STobias Grosser   ///
539aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
540aaabbbf8STobias Grosser   ///
541aaabbbf8STobias Grosser   /// Example:
542aaabbbf8STobias Grosser   ///
543aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
544aaabbbf8STobias Grosser   ///     A[i + 42] += ...
545aaabbbf8STobias Grosser   ///
546aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
547aaabbbf8STobias Grosser   ///
548aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
549aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
550aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
551aaabbbf8STobias Grosser 
55200bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
55300bb5a99STobias Grosser   ///
55400bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
55500bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
55600bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
55700bb5a99STobias Grosser 
55832837fe3STobias Grosser   /// Create kernel function.
55932837fe3STobias Grosser   ///
56032837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
56132837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
56232837fe3STobias Grosser   /// start block of this newly created function.
56332837fe3STobias Grosser   ///
56432837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
565edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
566f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
567f291c8d5SSiddharth Bhat   ///                         kernel.
568edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
569f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
570f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
57132837fe3STobias Grosser 
57232837fe3STobias Grosser   /// Create the declaration of a kernel function.
57332837fe3STobias Grosser   ///
57432837fe3STobias Grosser   /// The kernel function takes as arguments:
57532837fe3STobias Grosser   ///
57632837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
577f6044bd0STobias Grosser   ///   - Host iterators
578c84a1995STobias Grosser   ///   - Parameters
57932837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
58032837fe3STobias Grosser   ///
58132837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
582edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
583edb885cbSTobias Grosser   ///
58432837fe3STobias Grosser   /// @returns The newly declared function.
585edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
586edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
58732837fe3STobias Grosser 
588472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
589472f9654STobias Grosser   ///
590472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
591472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
592472f9654STobias Grosser 
5932f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5942f3073b5SPhilipp Schaad   ///
595d71493cbSPhilip Pfaffe   /// @param Kernel The kernel to generate the function calls for.
596d71493cbSPhilip Pfaffe   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
597d71493cbSPhilip Pfaffe   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
5982f3073b5SPhilipp Schaad 
599f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
600f291c8d5SSiddharth Bhat   ///
601f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
602f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
603f291c8d5SSiddharth Bhat   ///
604f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
605f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
606f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
607f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
608f291c8d5SSiddharth Bhat   ///
609f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
610f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
611f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
612f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
613f291c8d5SSiddharth Bhat   ///
614f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
615f291c8d5SSiddharth Bhat   ///                         this kernel.
616f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
617f291c8d5SSiddharth Bhat 
618b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
619b513b491STobias Grosser   ///
620b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
621b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
622b513b491STobias Grosser 
623edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
624edb885cbSTobias Grosser   ///
625edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
626edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
627edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
628edb885cbSTobias Grosser 
6295260c041STobias Grosser   /// Create an in-kernel synchronization call.
6305260c041STobias Grosser   void createKernelSync();
6315260c041STobias Grosser 
63274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
63374dc3cb4STobias Grosser   ///
63474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
63574dc3cb4STobias Grosser   std::string createKernelASM();
63674dc3cb4STobias Grosser 
63774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
63874dc3cb4STobias Grosser   ///
63974dc3cb4STobias Grosser   /// @param F The function to remove references to.
64074dc3cb4STobias Grosser   void clearDominators(Function *F);
64174dc3cb4STobias Grosser 
64274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
64374dc3cb4STobias Grosser   ///
64474dc3cb4STobias Grosser   /// @param F The function to remove references to.
64574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
64674dc3cb4STobias Grosser 
64774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
64874dc3cb4STobias Grosser   ///
64974dc3cb4STobias Grosser   /// @param F The function to remove references to.
65074dc3cb4STobias Grosser   void clearLoops(Function *F);
65174dc3cb4STobias Grosser 
6528fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6538fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6548fc6cdfbSTobias Grosser 
6558fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6568fc6cdfbSTobias Grosser   void addCUDALibDevice();
6578fc6cdfbSTobias Grosser 
65832837fe3STobias Grosser   /// Finalize the generation of the kernel function.
65932837fe3STobias Grosser   ///
66032837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
66132837fe3STobias Grosser   /// dump its IR to stderr.
66257793596STobias Grosser   ///
66357793596STobias Grosser   /// @returns The Assembly string of the kernel.
66457793596STobias Grosser   std::string finalizeKernelFunction();
665fa7b0802STobias Grosser 
66651dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
66751dfc275STobias Grosser   ///
66851dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
669a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
67051dfc275STobias Grosser   /// the kernel terminates.
67151dfc275STobias Grosser   ///
67251dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
67351dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
67451dfc275STobias Grosser 
6757287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
676fa7b0802STobias Grosser   void allocateDeviceArrays();
677fa7b0802STobias Grosser 
678b99c1171STobias Grosser   /// Create code to prepare the managed device pointers.
679b99c1171STobias Grosser   void prepareManagedDeviceArrays();
680b99c1171STobias Grosser 
6817287aeddSTobias Grosser   /// Free all allocated device arrays.
6827287aeddSTobias Grosser   void freeDeviceArrays();
6837287aeddSTobias Grosser 
684fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
685fa7b0802STobias Grosser   ///
686fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
687fa7b0802STobias Grosser   Value *createCallInitContext();
688fa7b0802STobias Grosser 
68979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
69079a947c2STobias Grosser   ///
69179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
69279a947c2STobias Grosser   ///
69379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
69479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
69579a947c2STobias Grosser 
696fa7b0802STobias Grosser   /// Create a call to free the GPU context.
697fa7b0802STobias Grosser   ///
698fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
699fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
700fa7b0802STobias Grosser 
7017287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
7027287aeddSTobias Grosser   ///
7037287aeddSTobias Grosser   /// @param Size The size of memory to allocate
7047287aeddSTobias Grosser   ///
7057287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
706fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
7077287aeddSTobias Grosser 
7087287aeddSTobias Grosser   /// Create a call to free a device array.
7097287aeddSTobias Grosser   ///
7107287aeddSTobias Grosser   /// @param Array The device array to free.
7117287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
71213c78e4dSTobias Grosser 
71313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
71413c78e4dSTobias Grosser   ///
71513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
71613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
71713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
71813c78e4dSTobias Grosser                                       Value *Size);
71913c78e4dSTobias Grosser 
72013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
72113c78e4dSTobias Grosser   ///
72213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
72313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
72413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
72513c78e4dSTobias Grosser                                       Value *Size);
72657793596STobias Grosser 
727abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
728abed4969SSiddharth Bhat   /// \note
729abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
730abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
731abed4969SSiddharth Bhat 
73257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
73357793596STobias Grosser   ///
73457793596STobias Grosser   /// @param Buffer The string describing the kernel.
73557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
73657793596STobias Grosser   ///
73757793596STobias Grosser   /// @returns A pointer to a kernel object
73857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
73957793596STobias Grosser 
74057793596STobias Grosser   /// Create a call to free a GPU kernel.
74157793596STobias Grosser   ///
74257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
74357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
74479a947c2STobias Grosser 
74579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
74679a947c2STobias Grosser   ///
74779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
74879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
74979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
75079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
75179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
75279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
753a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
75479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
75579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
75679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
75779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
75879a947c2STobias Grosser                               Value *Parameters);
7591fb9b64dSTobias Grosser };
7601fb9b64dSTobias Grosser 
76179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7621abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7631abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
76479f13b9aSSingapuram Sanjay Srivallabh }
76579f13b9aSSingapuram Sanjay Srivallabh 
766fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
767750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
768750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
769750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
770750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
771750160e2STobias Grosser 
772fa7b0802STobias Grosser   GPUContext = createCallInitContext();
773abed4969SSiddharth Bhat 
774c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
775fa7b0802STobias Grosser     allocateDeviceArrays();
776b99c1171STobias Grosser   else
777b99c1171STobias Grosser     prepareManagedDeviceArrays();
778fa7b0802STobias Grosser }
779fa7b0802STobias Grosser 
780fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
781c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
7827287aeddSTobias Grosser     freeDeviceArrays();
783abed4969SSiddharth Bhat 
784fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
785fa7b0802STobias Grosser   IslNodeBuilder::finalize();
786fa7b0802STobias Grosser }
787fa7b0802STobias Grosser 
788fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
789c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
790c4a4af47SSiddharth Bhat          "Managed memory will directly send host pointers "
791abed4969SSiddharth Bhat          "to the kernel. There is no need for device arrays");
7928ea1fc19STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
793fa7b0802STobias Grosser 
794fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
795fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
79613c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7977287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7987287aeddSTobias Grosser     DevArrayName.append(Array->name);
799fa7b0802STobias Grosser 
80013c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
801aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
802aaabbbf8STobias Grosser     if (Offset)
803aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
804aaabbbf8STobias Grosser           ArraySize,
805aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
806aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
80734eeabbcSSiddharth Bhat     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
80834eeabbcSSiddharth Bhat     // It makes no sense to have an array of size 0. The CUDA API will
80934eeabbcSSiddharth Bhat     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
81034eeabbcSSiddharth Bhat     // choose to be defensive and catch this at the compile phase. It is
81134eeabbcSSiddharth Bhat     // most likely that we are doing something wrong with size computation.
81234eeabbcSSiddharth Bhat     if (SizeSCEV->isZero()) {
81334eeabbcSSiddharth Bhat       errs() << getUniqueScopName(&S)
81434eeabbcSSiddharth Bhat              << " has computed array size 0: " << *ArraySize
81534eeabbcSSiddharth Bhat              << " | for array: " << *(ScopArray->getBasePtr())
81634eeabbcSSiddharth Bhat              << ". This is illegal, exiting.\n";
81734eeabbcSSiddharth Bhat       report_fatal_error("array size was computed to be 0");
81834eeabbcSSiddharth Bhat     }
81934eeabbcSSiddharth Bhat 
8207287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
8217287aeddSTobias Grosser     DevArray->setName(DevArrayName);
82213c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
823fa7b0802STobias Grosser   }
824fa7b0802STobias Grosser 
825fa7b0802STobias Grosser   isl_ast_build_free(Build);
826fa7b0802STobias Grosser }
827fa7b0802STobias Grosser 
828b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() {
829c4a4af47SSiddharth Bhat   assert(PollyManagedMemory &&
830b99c1171STobias Grosser          "Device array most only be prepared in managed-memory mode");
831b99c1171STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
832b99c1171STobias Grosser     gpu_array_info *Array = &Prog->array[i];
833b99c1171STobias Grosser     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
834b99c1171STobias Grosser     Value *HostPtr;
835b99c1171STobias Grosser 
836b99c1171STobias Grosser     if (gpu_array_is_scalar(Array))
837b99c1171STobias Grosser       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
838b99c1171STobias Grosser     else
839b99c1171STobias Grosser       HostPtr = ScopArray->getBasePtr();
840b99c1171STobias Grosser     HostPtr = getLatestValue(HostPtr);
841b99c1171STobias Grosser 
842b99c1171STobias Grosser     Value *Offset = getArrayOffset(Array);
843b99c1171STobias Grosser     if (Offset) {
844b99c1171STobias Grosser       HostPtr = Builder.CreatePointerCast(
845b99c1171STobias Grosser           HostPtr, ScopArray->getElementType()->getPointerTo());
8460ce9acf6SEli Friedman       HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
847b99c1171STobias Grosser     }
848b99c1171STobias Grosser 
849b99c1171STobias Grosser     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
850b99c1171STobias Grosser     DeviceAllocations[ScopArray] = HostPtr;
851b99c1171STobias Grosser   }
852b99c1171STobias Grosser }
853b99c1171STobias Grosser 
854c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
855c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
856c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
857c1c6a2a6STobias Grosser 
858c1c6a2a6STobias Grosser   for (auto &F : *M) {
859c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
860c1c6a2a6STobias Grosser       continue;
861c1c6a2a6STobias Grosser 
862c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
863c1c6a2a6STobias Grosser 
864c1c6a2a6STobias Grosser     Metadata *Elements[] = {
865c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
866c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
867c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
868c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
869c1c6a2a6STobias Grosser     };
870c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
871c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
872c1c6a2a6STobias Grosser   }
873c1c6a2a6STobias Grosser }
874c1c6a2a6STobias Grosser 
8757287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
876c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
87713c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
87813c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8797287aeddSTobias Grosser }
8807287aeddSTobias Grosser 
88157793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
88257793596STobias Grosser   const char *Name = "polly_getKernel";
88357793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
88457793596STobias Grosser   Function *F = M->getFunction(Name);
88557793596STobias Grosser 
88657793596STobias Grosser   // If F is not available, declare it.
88757793596STobias Grosser   if (!F) {
88857793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
88957793596STobias Grosser     std::vector<Type *> Args;
89057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89257793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
89357793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
89457793596STobias Grosser   }
89557793596STobias Grosser 
89657793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
89757793596STobias Grosser }
89857793596STobias Grosser 
89979a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
90079a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
90179a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90279a947c2STobias Grosser   Function *F = M->getFunction(Name);
90379a947c2STobias Grosser 
90479a947c2STobias Grosser   // If F is not available, declare it.
90579a947c2STobias Grosser   if (!F) {
90679a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
90779a947c2STobias Grosser     std::vector<Type *> Args;
90879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
90979a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
91079a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
91179a947c2STobias Grosser   }
91279a947c2STobias Grosser 
91379a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
91479a947c2STobias Grosser }
91579a947c2STobias Grosser 
91679a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
91779a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
91879a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
91979a947c2STobias Grosser                                             Value *Parameters) {
92079a947c2STobias Grosser   const char *Name = "polly_launchKernel";
92179a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92279a947c2STobias Grosser   Function *F = M->getFunction(Name);
92379a947c2STobias Grosser 
92479a947c2STobias Grosser   // If F is not available, declare it.
92579a947c2STobias Grosser   if (!F) {
92679a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
92779a947c2STobias Grosser     std::vector<Type *> Args;
92879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
92979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93479a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93579a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
93679a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
93779a947c2STobias Grosser   }
93879a947c2STobias Grosser 
939ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
94079a947c2STobias Grosser                          BlockDimZ, Parameters});
94179a947c2STobias Grosser }
94279a947c2STobias Grosser 
94357793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
94457793596STobias Grosser   const char *Name = "polly_freeKernel";
94557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
94657793596STobias Grosser   Function *F = M->getFunction(Name);
94757793596STobias Grosser 
94857793596STobias Grosser   // If F is not available, declare it.
94957793596STobias Grosser   if (!F) {
95057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
95157793596STobias Grosser     std::vector<Type *> Args;
95257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95357793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
95457793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
95557793596STobias Grosser   }
95657793596STobias Grosser 
95757793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
95857793596STobias Grosser }
95957793596STobias Grosser 
9607287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
961c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
962c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
963abed4969SSiddharth Bhat          "for device");
9647287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
9657287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9667287aeddSTobias Grosser   Function *F = M->getFunction(Name);
9677287aeddSTobias Grosser 
9687287aeddSTobias Grosser   // If F is not available, declare it.
9697287aeddSTobias Grosser   if (!F) {
9707287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9717287aeddSTobias Grosser     std::vector<Type *> Args;
9727287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9737287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9747287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9757287aeddSTobias Grosser   }
9767287aeddSTobias Grosser 
9777287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9787287aeddSTobias Grosser }
9797287aeddSTobias Grosser 
980fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
981c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
982c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
983abed4969SSiddharth Bhat          "for device");
984fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
985fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
986fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
987fa7b0802STobias Grosser 
988fa7b0802STobias Grosser   // If F is not available, declare it.
989fa7b0802STobias Grosser   if (!F) {
990fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
991fa7b0802STobias Grosser     std::vector<Type *> Args;
992fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
993fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
994fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
995fa7b0802STobias Grosser   }
996fa7b0802STobias Grosser 
997fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
998fa7b0802STobias Grosser }
999fa7b0802STobias Grosser 
100013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
100113c78e4dSTobias Grosser                                                     Value *DeviceData,
100213c78e4dSTobias Grosser                                                     Value *Size) {
1003c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1004c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1005abed4969SSiddharth Bhat          "device and host");
100613c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
100713c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
100813c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
100913c78e4dSTobias Grosser 
101013c78e4dSTobias Grosser   // If F is not available, declare it.
101113c78e4dSTobias Grosser   if (!F) {
101213c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
101313c78e4dSTobias Grosser     std::vector<Type *> Args;
101413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
101513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
101613c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
101713c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
101813c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
101913c78e4dSTobias Grosser   }
102013c78e4dSTobias Grosser 
102113c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
102213c78e4dSTobias Grosser }
102313c78e4dSTobias Grosser 
102413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
102513c78e4dSTobias Grosser                                                     Value *HostData,
102613c78e4dSTobias Grosser                                                     Value *Size) {
1027c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1028c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1029abed4969SSiddharth Bhat          "device and host");
103013c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
103113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
103213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
103313c78e4dSTobias Grosser 
103413c78e4dSTobias Grosser   // If F is not available, declare it.
103513c78e4dSTobias Grosser   if (!F) {
103613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
103713c78e4dSTobias Grosser     std::vector<Type *> Args;
103813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
103913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
104013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
104113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
104213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
104313c78e4dSTobias Grosser   }
104413c78e4dSTobias Grosser 
104513c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
104613c78e4dSTobias Grosser }
104713c78e4dSTobias Grosser 
1048abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
1049c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1050abed4969SSiddharth Bhat                                "managed memory");
1051abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
1052abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1053abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
1054abed4969SSiddharth Bhat 
1055abed4969SSiddharth Bhat   // If F is not available, declare it.
1056abed4969SSiddharth Bhat   if (!F) {
1057abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1058abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1059abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
1060abed4969SSiddharth Bhat   }
1061abed4969SSiddharth Bhat 
1062abed4969SSiddharth Bhat   Builder.CreateCall(F);
1063abed4969SSiddharth Bhat }
1064abed4969SSiddharth Bhat 
1065fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
106617f01968SSiddharth Bhat   const char *Name;
106717f01968SSiddharth Bhat 
106817f01968SSiddharth Bhat   switch (Runtime) {
106917f01968SSiddharth Bhat   case GPURuntime::CUDA:
107017f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
107117f01968SSiddharth Bhat     break;
107217f01968SSiddharth Bhat   case GPURuntime::OpenCL:
107317f01968SSiddharth Bhat     Name = "polly_initContextCL";
107417f01968SSiddharth Bhat     break;
107517f01968SSiddharth Bhat   }
107617f01968SSiddharth Bhat 
1077fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1078fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1079fa7b0802STobias Grosser 
1080fa7b0802STobias Grosser   // If F is not available, declare it.
1081fa7b0802STobias Grosser   if (!F) {
1082fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1083fa7b0802STobias Grosser     std::vector<Type *> Args;
1084fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1085fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1086fa7b0802STobias Grosser   }
1087fa7b0802STobias Grosser 
1088fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1089fa7b0802STobias Grosser }
1090fa7b0802STobias Grosser 
1091fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1092fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1093fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1094fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1095fa7b0802STobias Grosser 
1096fa7b0802STobias Grosser   // If F is not available, declare it.
1097fa7b0802STobias Grosser   if (!F) {
1098fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1099fa7b0802STobias Grosser     std::vector<Type *> Args;
1100fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1101fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1102fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1103fa7b0802STobias Grosser   }
1104fa7b0802STobias Grosser 
1105fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1106fa7b0802STobias Grosser }
1107fa7b0802STobias Grosser 
11085260c041STobias Grosser /// Check if one string is a prefix of another.
11095260c041STobias Grosser ///
11105260c041STobias Grosser /// @param String The string in which to look for the prefix.
11115260c041STobias Grosser /// @param Prefix The prefix to look for.
11125260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
11135260c041STobias Grosser   return String.find(Prefix) == 0;
11145260c041STobias Grosser }
11155260c041STobias Grosser 
111613c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1117b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
111813c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
111913c78e4dSTobias Grosser 
112013c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1121718d04c6STobias Grosser     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1122f7face4bSSiddharth Bhat 
1123d3fdbda6SRiccardo Mori     isl::pw_aff OffsetDimZero = ArrayBound.at(0);
1124f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
112513c78e4dSTobias Grosser 
112613c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1127d3fdbda6SRiccardo Mori       isl::pw_aff Bound_I = ArrayBound.at(i);
1128f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1129f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
113013c78e4dSTobias Grosser     }
113113c78e4dSTobias Grosser 
1132f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1133b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1134b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
113513c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
113613c78e4dSTobias Grosser   }
113713c78e4dSTobias Grosser   return ArraySize;
113813c78e4dSTobias Grosser }
113913c78e4dSTobias Grosser 
1140aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1141aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1142aaabbbf8STobias Grosser     return nullptr;
1143aaabbbf8STobias Grosser 
1144b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1145aaabbbf8STobias Grosser 
1146718d04c6STobias Grosser   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1147aaabbbf8STobias Grosser 
1148ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1149aaabbbf8STobias Grosser 
115044596fe6SRiccardo Mori   for (unsigned i : rangeIslSize(0, Min.tuple_dim()))
1151ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1152aaabbbf8STobias Grosser 
1153ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1154aaabbbf8STobias Grosser     return nullptr;
1155aaabbbf8STobias Grosser   }
1156aaabbbf8STobias Grosser 
11570813bd16SRiccardo Mori   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.ctx(), 0));
1158aaabbbf8STobias Grosser 
115944596fe6SRiccardo Mori   for (unsigned i : rangeIslSize(0, Min.tuple_dim())) {
1160aaabbbf8STobias Grosser     if (i > 0) {
1161ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1162ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1163ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1164ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1165aaabbbf8STobias Grosser     }
1166ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1167ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1168ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1169aaabbbf8STobias Grosser   }
1170aaabbbf8STobias Grosser 
1171ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1172aaabbbf8STobias Grosser }
1173aaabbbf8STobias Grosser 
1174b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1175abed4969SSiddharth Bhat                                              ScopArrayInfo *ArrayInfo) {
1176c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "Only used when you wish to get a host "
1177abed4969SSiddharth Bhat                                "pointer for sending data to the kernel, "
1178abed4969SSiddharth Bhat                                "with managed memory");
1179abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1180b99c1171STobias Grosser   it = DeviceAllocations.find(ArrayInfo);
1181b99c1171STobias Grosser   assert(it != DeviceAllocations.end() &&
1182b99c1171STobias Grosser          "Device array expected to be available");
1183abed4969SSiddharth Bhat   return it->second;
1184abed4969SSiddharth Bhat }
1185abed4969SSiddharth Bhat 
118613c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
118713c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1188c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
118913c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
119013c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
119113c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
119213c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
119313c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
119413c78e4dSTobias Grosser 
119513c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1196aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
119713c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
119813c78e4dSTobias Grosser 
1199b06ff457STobias Grosser   Value *HostPtr;
1200b06ff457STobias Grosser 
1201b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1202b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1203b06ff457STobias Grosser   else
1204b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1205edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
120613c78e4dSTobias Grosser 
1207aaabbbf8STobias Grosser   if (Offset) {
1208aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1209aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
12100ce9acf6SEli Friedman     HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
1211aaabbbf8STobias Grosser   }
1212aaabbbf8STobias Grosser 
121313c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
121413c78e4dSTobias Grosser 
1215aaabbbf8STobias Grosser   if (Offset) {
1216aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1217ff40087aSTobias Grosser         Size, Builder.CreateMul(
1218ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1219aaabbbf8STobias Grosser   }
1220aaabbbf8STobias Grosser 
122113c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
122213c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
122313c78e4dSTobias Grosser   else
122413c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
122513c78e4dSTobias Grosser 
122613c78e4dSTobias Grosser   isl_id_free(Id);
122713c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
122813c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
122913c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
123013c78e4dSTobias Grosser }
123113c78e4dSTobias Grosser 
12321fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
123332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
123432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
123532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
123632837fe3STobias Grosser   isl_id_free(Id);
123732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
123832837fe3STobias Grosser 
123932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
124032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
124132837fe3STobias Grosser     createKernel(UserStmt);
124262acb344STobias Grosser     if (PollyManagedMemory)
124362acb344STobias Grosser       createCallSynchronizeDevice();
124432837fe3STobias Grosser     isl_ast_expr_free(Expr);
124532837fe3STobias Grosser     return;
124632837fe3STobias Grosser   }
12479e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
12489e3db2b7SSiddharth Bhat     initializeAfterRTH();
12499e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12509e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12519e3db2b7SSiddharth Bhat     return;
12529e3db2b7SSiddharth Bhat   }
12539e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12549e3db2b7SSiddharth Bhat     finalize();
12559e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12569e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12579e3db2b7SSiddharth Bhat     return;
12589e3db2b7SSiddharth Bhat   }
125913c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1260c4a4af47SSiddharth Bhat     if (!PollyManagedMemory)
126113c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1262abed4969SSiddharth Bhat     else
1263abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1264abed4969SSiddharth Bhat 
126532837fe3STobias Grosser     isl_ast_expr_free(Expr);
126613c78e4dSTobias Grosser     return;
126713c78e4dSTobias Grosser   }
126813c78e4dSTobias Grosser 
126913c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1270c4a4af47SSiddharth Bhat     if (!PollyManagedMemory) {
127113c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1272abed4969SSiddharth Bhat     } else {
1273abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1274abed4969SSiddharth Bhat     }
127513c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
127638fc0aedSTobias Grosser     return;
127738fc0aedSTobias Grosser   }
127838fc0aedSTobias Grosser 
12795260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12805260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12815260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12825260c041STobias Grosser   isl_id_free(Anno);
12835260c041STobias Grosser 
12845260c041STobias Grosser   switch (KernelStmt->type) {
12855260c041STobias Grosser   case ppcg_kernel_domain:
1286edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12875260c041STobias Grosser     isl_ast_node_free(UserStmt);
12885260c041STobias Grosser     return;
12895260c041STobias Grosser   case ppcg_kernel_copy:
1290b513b491STobias Grosser     createKernelCopy(KernelStmt);
12915260c041STobias Grosser     isl_ast_expr_free(Expr);
12925260c041STobias Grosser     isl_ast_node_free(UserStmt);
12935260c041STobias Grosser     return;
12945260c041STobias Grosser   case ppcg_kernel_sync:
12955260c041STobias Grosser     createKernelSync();
12965260c041STobias Grosser     isl_ast_expr_free(Expr);
12975260c041STobias Grosser     isl_ast_node_free(UserStmt);
12985260c041STobias Grosser     return;
12995260c041STobias Grosser   }
13005260c041STobias Grosser 
13015260c041STobias Grosser   isl_ast_expr_free(Expr);
13025260c041STobias Grosser   isl_ast_node_free(UserStmt);
13035260c041STobias Grosser }
130453c80387SPhilip Pfaffe 
130553c80387SPhilip Pfaffe void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
1306d3fdbda6SRiccardo Mori   createForSequential(isl::manage(Node).as<isl::ast_node_for>(), false);
130753c80387SPhilip Pfaffe }
130853c80387SPhilip Pfaffe 
1309b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1310b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1311880014b5SNikita Popov   auto LocalAddr = ExprBuilder.createAccessAddress(LocalIndex);
1312b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1313880014b5SNikita Popov   auto GlobalAddr = ExprBuilder.createAccessAddress(Index);
1314b513b491STobias Grosser 
1315b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1316880014b5SNikita Popov     LoadInst *Load =
1317880014b5SNikita Popov         Builder.CreateLoad(GlobalAddr.second, GlobalAddr.first, "shared.read");
1318880014b5SNikita Popov     Builder.CreateStore(Load, LocalAddr.first);
1319b513b491STobias Grosser   } else {
1320880014b5SNikita Popov     LoadInst *Load =
1321880014b5SNikita Popov         Builder.CreateLoad(LocalAddr.second, LocalAddr.first, "shared.write");
1322880014b5SNikita Popov     Builder.CreateStore(Load, GlobalAddr.first);
1323b513b491STobias Grosser   }
1324b513b491STobias Grosser }
13255260c041STobias Grosser 
1326edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1327edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1328edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1329edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1330edb885cbSTobias Grosser 
1331edb885cbSTobias Grosser   LoopToScevMapT LTS;
1332edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1333edb885cbSTobias Grosser 
1334edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1335edb885cbSTobias Grosser 
1336edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1337edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1338edb885cbSTobias Grosser   else
1339a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1340edb885cbSTobias Grosser }
1341edb885cbSTobias Grosser 
13425260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
13435260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13442f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
134517f01968SSiddharth Bhat 
134617f01968SSiddharth Bhat   Function *Sync;
134717f01968SSiddharth Bhat 
134817f01968SSiddharth Bhat   switch (Arch) {
13492f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
13502f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
13512f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
13522f3073b5SPhilipp Schaad 
13532f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
13542f3073b5SPhilipp Schaad     if (!Sync) {
13552f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13562f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13572f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13582f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13592f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13602f3073b5SPhilipp Schaad     }
13612f3073b5SPhilipp Schaad     break;
136217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
136317f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
136417f01968SSiddharth Bhat     break;
136517f01968SSiddharth Bhat   }
136617f01968SSiddharth Bhat 
13675260c041STobias Grosser   Builder.CreateCall(Sync, {});
13685260c041STobias Grosser }
13695260c041STobias Grosser 
1370edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1371edb885cbSTobias Grosser ///
1372edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1373edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1374edb885cbSTobias Grosser ///
1375edb885cbSTobias Grosser /// @param Node The node to collect references for.
1376edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1377edb885cbSTobias Grosser ///
1378edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1379edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1380edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1381edb885cbSTobias Grosser     return isl_bool_true;
1382edb885cbSTobias Grosser 
1383edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1384edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1385edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1386edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1387edb885cbSTobias Grosser   isl_id_free(Id);
1388edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1389edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1390edb885cbSTobias Grosser 
1391edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1392edb885cbSTobias Grosser     return isl_bool_true;
1393edb885cbSTobias Grosser 
1394edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1395edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1396edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1397edb885cbSTobias Grosser   isl_id_free(Id);
1398edb885cbSTobias Grosser 
139900bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1400edb885cbSTobias Grosser 
1401edb885cbSTobias Grosser   return isl_bool_true;
1402edb885cbSTobias Grosser }
1403edb885cbSTobias Grosser 
14048fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
14058fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
140656572c6aSSiddharth Bhat     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
140756572c6aSSiddharth Bhat     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
140856572c6aSSiddharth Bhat 
140956572c6aSSiddharth Bhat // A map from intrinsics to their corresponding libdevice functions.
141056572c6aSSiddharth Bhat const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
141156572c6aSSiddharth Bhat     {"llvm.exp.f64", "exp"},
141256572c6aSSiddharth Bhat     {"llvm.exp.f32", "expf"},
14136aac2773SBjorn Pettersson     {"llvm.powi.f64.i32", "powi"},
14146aac2773SBjorn Pettersson     {"llvm.powi.f32.i32", "powif"}};
14158fc6cdfbSTobias Grosser 
141666a05ad6SPhilip Pfaffe /// Return the corresponding CUDA libdevice function name @p Name.
141756572c6aSSiddharth Bhat /// Note that this function will try to convert instrinsics in the list
141856572c6aSSiddharth Bhat /// IntrinsicToLibdeviceFunc into libdevice functions.
141956572c6aSSiddharth Bhat /// This is because some intrinsics such as `exp`
142056572c6aSSiddharth Bhat /// are not supported by the NVPTX backend.
142156572c6aSSiddharth Bhat /// If this restriction of the backend is lifted, we should refactor our code
142256572c6aSSiddharth Bhat /// so that we use intrinsics whenever possible.
14238fc6cdfbSTobias Grosser ///
14248fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
14251a53b732SMichael Kruse std::string getCUDALibDeviceFuntion(StringRef NameRef) {
14261a53b732SMichael Kruse   std::string Name = NameRef.str();
142766a05ad6SPhilip Pfaffe   auto It = IntrinsicToLibdeviceFunc.find(Name);
142856572c6aSSiddharth Bhat   if (It != IntrinsicToLibdeviceFunc.end())
142966a05ad6SPhilip Pfaffe     return getCUDALibDeviceFuntion(It->second);
143056572c6aSSiddharth Bhat 
143166a05ad6SPhilip Pfaffe   if (CUDALibDeviceFunctions.count(Name))
14321a53b732SMichael Kruse     return ("__nv_" + Name);
14338fc6cdfbSTobias Grosser 
14348fc6cdfbSTobias Grosser   return "";
14358fc6cdfbSTobias Grosser }
14368fc6cdfbSTobias Grosser 
1437f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
14388fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1439f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1440f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
144154491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
144254491db6STobias Grosser   // "llvm.copysign".
144354491db6STobias Grosser   const StringRef Name = F->getName();
14448fc6cdfbSTobias Grosser 
144566a05ad6SPhilip Pfaffe   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
14468fc6cdfbSTobias Grosser     return true;
14478fc6cdfbSTobias Grosser 
144854491db6STobias Grosser   return F->isIntrinsic() &&
144954491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
145056572c6aSSiddharth Bhat           Name.startswith("llvm.copysign"));
1451f291c8d5SSiddharth Bhat }
1452f291c8d5SSiddharth Bhat 
1453f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1454f291c8d5SSiddharth Bhat ///
1455f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1456f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1457f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1458f291c8d5SSiddharth Bhat /// `Function`s.
1459f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1460f291c8d5SSiddharth Bhat 
1461f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1462f291c8d5SSiddharth Bhat static SetVector<Function *>
14638fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
14648fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1465f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1466f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1467f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1468f291c8d5SSiddharth Bhat     if (F) {
14698fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
14708fc6cdfbSTobias Grosser              "Code should have bailed out by "
1471f291c8d5SSiddharth Bhat              "this point if an invalid function "
1472f291c8d5SSiddharth Bhat              "were present in a kernel.");
1473f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1474f291c8d5SSiddharth Bhat     }
1475f291c8d5SSiddharth Bhat   }
1476f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1477f291c8d5SSiddharth Bhat }
1478f291c8d5SSiddharth Bhat 
147943df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
148043df2020STobias Grosser            isl::space>
1481f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1482edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1483edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1484edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
148543df2020STobias Grosser   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1486edb885cbSTobias Grosser   SubtreeReferences References = {
148743df2020STobias Grosser       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
148843df2020STobias Grosser       &ParamSpace};
1489edb885cbSTobias Grosser 
1490edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1491edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1492edb885cbSTobias Grosser 
1493e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1494e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1495e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1496e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1497e53c924bSSiddharth Bhat 
1498edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1499edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1500edb885cbSTobias Grosser 
1501e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1502edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1503e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1504e53c924bSSiddharth Bhat   }
1505e53c924bSSiddharth Bhat 
1506e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1507e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1508e53c924bSSiddharth Bhat   });
1509edb885cbSTobias Grosser 
1510edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1511d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1512edb885cbSTobias Grosser 
1513b65ccc43STobias Grosser   isl_space *Space = S.getParamSpace().release();
15143044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1515edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1516edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1517edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1518edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1519edb885cbSTobias Grosser     isl_id_free(Id);
1520edb885cbSTobias Grosser   }
1521edb885cbSTobias Grosser   isl_space_free(Space);
1522edb885cbSTobias Grosser 
15233044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1524edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1525edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1526edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1527edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1528edb885cbSTobias Grosser     isl_id_free(Id);
1529edb885cbSTobias Grosser   }
1530edb885cbSTobias Grosser 
1531f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1532f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1533f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1534f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1535f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1536f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1537f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1538f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1539f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
15408fc6cdfbSTobias Grosser 
15418fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
15428fc6cdfbSTobias Grosser 
1543f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
15448fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1545f291c8d5SSiddharth Bhat 
1546a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1547a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1548a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1549a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1550a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1551a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1552a1b2086aSSiddharth Bhat     else
1553a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1554a1b2086aSSiddharth Bhat   }
155543df2020STobias Grosser   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
155643df2020STobias Grosser                          ParamSpace);
1557edb885cbSTobias Grosser }
1558edb885cbSTobias Grosser 
155974dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
156074dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
156174dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
156274dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
156374dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
156474dc3cb4STobias Grosser 
156574dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
156674dc3cb4STobias Grosser     DT.eraseNode(BB);
156774dc3cb4STobias Grosser }
156874dc3cb4STobias Grosser 
156974dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
15704d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15714d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
157274dc3cb4STobias Grosser     if (L)
157374dc3cb4STobias Grosser       SE.forgetLoop(L);
157474dc3cb4STobias Grosser   }
15754d50ab86SPhilip Pfaffe }
157674dc3cb4STobias Grosser 
157774dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
1578c06a6380SPhilip Pfaffe   SmallSet<Loop *, 1> WorkList;
15794d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15804d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
15814d50ab86SPhilip Pfaffe     if (L)
1582c06a6380SPhilip Pfaffe       WorkList.insert(L);
15834d50ab86SPhilip Pfaffe   }
1584c06a6380SPhilip Pfaffe   for (auto *L : WorkList)
1585c06a6380SPhilip Pfaffe     LI.erase(L);
158674dc3cb4STobias Grosser }
158774dc3cb4STobias Grosser 
158879a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
158979a947c2STobias Grosser   std::vector<Value *> Sizes;
15908ea1fc19STobias Grosser   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
159179a947c2STobias Grosser 
1592718d04c6STobias Grosser   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
159379a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
1594d3fdbda6SRiccardo Mori     isl::pw_aff Size = GridSizePwAffs.at(i);
15954d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15964d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
159779a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
159879a947c2STobias Grosser     Sizes.push_back(Res);
159979a947c2STobias Grosser   }
160079a947c2STobias Grosser 
160179a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
160279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
160379a947c2STobias Grosser 
160479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
160579a947c2STobias Grosser }
160679a947c2STobias Grosser 
160779a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
160879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
160979a947c2STobias Grosser   std::vector<Value *> Sizes;
161079a947c2STobias Grosser 
161179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
161279a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
161379a947c2STobias Grosser     Sizes.push_back(Res);
161479a947c2STobias Grosser   }
161579a947c2STobias Grosser 
161679a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
161779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
161879a947c2STobias Grosser 
161979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
162079a947c2STobias Grosser }
162179a947c2STobias Grosser 
1622ee6bd28fSNikita Popov void GPUNodeBuilder::insertStoreParameter(Type *ArrayTy,
1623ee6bd28fSNikita Popov                                           Instruction *Parameters,
1624a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1625a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1626ee6bd28fSNikita Popov       ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1627a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1628a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1629a90be207SSiddharth Bhat }
1630a90be207SSiddharth Bhat 
163157693272STobias Grosser Value *
163257693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
163357693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1634a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1635a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1636a90be207SSiddharth Bhat 
163750139f0fSPhilipp Schaad   // If we are using the OpenCL Runtime, we need to add the kernel argument
163850139f0fSPhilipp Schaad   // sizes to the end of the launch-parameter list, so OpenCL can determine
163950139f0fSPhilipp Schaad   // how big the respective kernel arguments are.
164050139f0fSPhilipp Schaad   // Here we need to reserve adequate space for that.
164150139f0fSPhilipp Schaad   Type *ArrayTy;
164250139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL)
164350139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
164450139f0fSPhilipp Schaad   else
164550139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
164679a947c2STobias Grosser 
164779a947c2STobias Grosser   BasicBlock *EntryBlock =
164879a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
164967726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
165079a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
165167726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
165267726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
165379a947c2STobias Grosser 
165479a947c2STobias Grosser   int Index = 0;
165579a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
165679a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
165779a947c2STobias Grosser       continue;
165879a947c2STobias Grosser 
165979a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1660206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
166179a947c2STobias Grosser 
166250139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1663a90be207SSiddharth Bhat       ArgSizes[Index] = SAI->getElemSizeInBytes();
1664a90be207SSiddharth Bhat 
1665abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1666c4a4af47SSiddharth Bhat     if (PollyManagedMemory) {
1667b99c1171STobias Grosser       DevArray = getManagedDeviceArray(&Prog->array[i],
1668b99c1171STobias Grosser                                        const_cast<ScopArrayInfo *>(SAI));
1669abed4969SSiddharth Bhat     } else {
1670abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
167179a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1672abed4969SSiddharth Bhat     }
1673abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1674abed4969SSiddharth Bhat                                   "initialized");
1675aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1676aaabbbf8STobias Grosser 
1677aaabbbf8STobias Grosser     if (Offset) {
1678aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1679aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
16800ce9acf6SEli Friedman       DevArray = Builder.CreateGEP(SAI->getElementType(), DevArray,
16810ce9acf6SEli Friedman                                    Builder.CreateNeg(Offset));
1682aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1683aaabbbf8STobias Grosser     }
1684fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
16850ce9acf6SEli Friedman         ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1686aaabbbf8STobias Grosser 
1687fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1688abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1689c4a4af47SSiddharth Bhat       if (PollyManagedMemory)
1690abed4969SSiddharth Bhat         ValPtr = DevArray;
1691abed4969SSiddharth Bhat       else
1692abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1693abed4969SSiddharth Bhat 
1694abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1695abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1696fe74a7a1STobias Grosser       Value *ValPtrCast =
1697fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1698fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1699fe74a7a1STobias Grosser     } else {
170067726b32STobias Grosser       Instruction *Param =
170167726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
170267726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
170379a947c2STobias Grosser                          EntryBlock->getTerminator());
170479a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
170579a947c2STobias Grosser       Value *ParamTyped =
170679a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
170779a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1708fe74a7a1STobias Grosser     }
170979a947c2STobias Grosser     Index++;
171079a947c2STobias Grosser   }
171179a947c2STobias Grosser 
1712a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1713a490147cSTobias Grosser 
1714a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1715a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1716a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1717a490147cSTobias Grosser     isl_id_free(Id);
1718a90be207SSiddharth Bhat 
171950139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1720a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1721a90be207SSiddharth Bhat 
172267726b32STobias Grosser     Instruction *Param =
172367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
172467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1725a490147cSTobias Grosser                        EntryBlock->getTerminator());
1726a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1727ee6bd28fSNikita Popov     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1728a490147cSTobias Grosser     Index++;
1729a490147cSTobias Grosser   }
1730a490147cSTobias Grosser 
1731d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1732d8b94bcaSTobias Grosser 
1733d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1734d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1735d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1736a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1737a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1738d8b94bcaSTobias Grosser     isl_id_free(Id);
1739a90be207SSiddharth Bhat 
174050139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1741a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1742a90be207SSiddharth Bhat 
174367726b32STobias Grosser     Instruction *Param =
174467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
174567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1746d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1747d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1748ee6bd28fSNikita Popov     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1749d8b94bcaSTobias Grosser     Index++;
1750d8b94bcaSTobias Grosser   }
1751d8b94bcaSTobias Grosser 
175257693272STobias Grosser   for (auto Val : SubtreeValues) {
175350139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1754a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1755a90be207SSiddharth Bhat 
175667726b32STobias Grosser     Instruction *Param =
175767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
175867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
175957693272STobias Grosser                        EntryBlock->getTerminator());
176057693272STobias Grosser     Builder.CreateStore(Val, Param);
1761ee6bd28fSNikita Popov     insertStoreParameter(ArrayTy, Parameters, Param, Index);
1762a90be207SSiddharth Bhat     Index++;
1763a90be207SSiddharth Bhat   }
1764a90be207SSiddharth Bhat 
176550139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL) {
1766a90be207SSiddharth Bhat     for (int i = 0; i < NumArgs; i++) {
1767a90be207SSiddharth Bhat       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1768a90be207SSiddharth Bhat       Instruction *Param =
1769a90be207SSiddharth Bhat           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1770a90be207SSiddharth Bhat                          Launch + "_param_size_" + std::to_string(i),
1771a90be207SSiddharth Bhat                          EntryBlock->getTerminator());
1772a90be207SSiddharth Bhat       Builder.CreateStore(Val, Param);
1773ee6bd28fSNikita Popov       insertStoreParameter(ArrayTy, Parameters, Param, Index);
177457693272STobias Grosser       Index++;
177557693272STobias Grosser     }
177650139f0fSPhilipp Schaad   }
177757693272STobias Grosser 
177879a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
177979a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
178079a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
178179a947c2STobias Grosser }
178279a947c2STobias Grosser 
1783f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1784f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1785f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
17861a53b732SMichael Kruse     const std::string ClonedFnName = Fn->getName().str();
1787f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1788f291c8d5SSiddharth Bhat     if (!Clone)
1789f291c8d5SSiddharth Bhat       Clone =
1790f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1791f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1792f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1793f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1794f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1795f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1796f291c8d5SSiddharth Bhat   }
1797f291c8d5SSiddharth Bhat }
179832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
179932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
180032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
180132837fe3STobias Grosser   isl_id_free(Id);
180232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
180332837fe3STobias Grosser 
1804bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1805e8227804SMichael Kruse     DeepestParallel = std::max(
1806e8227804SMichael Kruse         DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1807bc653f20STobias Grosser   else
1808e8227804SMichael Kruse     DeepestSequential = std::max(
1809e8227804SMichael Kruse         DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1810bc653f20STobias Grosser 
1811c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1812c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1813c1c6a2a6STobias Grosser 
1814f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1815f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1816e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
181743df2020STobias Grosser   isl::space ParamSpace;
181843df2020STobias Grosser   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1819e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1820edb885cbSTobias Grosser 
182143df2020STobias Grosser   // Add parameters that appear only in the access function to the kernel
182243df2020STobias Grosser   // space. This is important to make sure that all isl_ids are passed as
182343df2020STobias Grosser   // parameters to the kernel, even though we may not have all parameters
182443df2020STobias Grosser   // in the context to improve compile time.
182543df2020STobias Grosser   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
182643df2020STobias Grosser 
182732837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
182832837fe3STobias Grosser 
182932837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1830472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1831edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1832587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1833b06ff457STobias Grosser   ScalarMap.clear();
1834c52b71dbSTobias Grosser   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1835c52b71dbSTobias Grosser   EscapeMap.clear();
183632837fe3STobias Grosser 
1837edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1838edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1839edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1840edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1841edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1842edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1843edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1844edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1845edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1846edb885cbSTobias Grosser     SubtreeValues.insert(V);
1847edb885cbSTobias Grosser   }
1848edb885cbSTobias Grosser 
1849f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1850f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
185132837fe3STobias Grosser 
185259ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
185359ab0705STobias Grosser 
185451dfc275STobias Grosser   finalizeKernelArguments(Kernel);
185574dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
18562f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1857c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
185874dc3cb4STobias Grosser   clearDominators(F);
185974dc3cb4STobias Grosser   clearScalarEvolution(F);
186074dc3cb4STobias Grosser   clearLoops(F);
186174dc3cb4STobias Grosser 
1862472f9654STobias Grosser   IDToValue = HostIDs;
186332837fe3STobias Grosser 
1864b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1865b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1866c52b71dbSTobias Grosser   EscapeMap = std::move(HostEscapeMap);
1867edb885cbSTobias Grosser   IDToSAI.clear();
186874dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
186974dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
18704d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
187174dc3cb4STobias Grosser   LocalArrays.clear();
1872edb885cbSTobias Grosser 
187351dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
187451dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
187557693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
187679a947c2STobias Grosser 
187779f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
187857793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
187957793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
188057793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
188179a947c2STobias Grosser 
188279a947c2STobias Grosser   Value *GridDimX, *GridDimY;
188379a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
188479a947c2STobias Grosser 
188579a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
188679a947c2STobias Grosser                          BlockDimZ, Parameters);
188757793596STobias Grosser   createCallFreeKernel(GPUKernel);
1888b513b491STobias Grosser 
1889b513b491STobias Grosser   for (auto Id : KernelIds)
1890b513b491STobias Grosser     isl_id_free(Id);
1891b513b491STobias Grosser 
1892b513b491STobias Grosser   KernelIds.clear();
189332837fe3STobias Grosser }
189432837fe3STobias Grosser 
189532837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
189632837fe3STobias Grosser ///
189732837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
189832837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1899d277fedaSSiddharth Bhat   std::string Ret = "";
190032837fe3STobias Grosser 
1901d277fedaSSiddharth Bhat   if (!is64Bit) {
1902d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190330caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1904d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1905d277fedaSSiddharth Bhat   } else {
1906d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1908d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1909d277fedaSSiddharth Bhat   }
191032837fe3STobias Grosser 
191132837fe3STobias Grosser   return Ret;
191232837fe3STobias Grosser }
191332837fe3STobias Grosser 
19142f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
19152f3073b5SPhilipp Schaad ///
19162f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
19172f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
19182f3073b5SPhilipp Schaad   std::string Ret = "";
19192f3073b5SPhilipp Schaad 
19202f3073b5SPhilipp Schaad   if (!is64Bit) {
19212f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
192230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19232f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19242f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19252f3073b5SPhilipp Schaad   } else {
19262f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
192730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19282f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19292f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19302f3073b5SPhilipp Schaad   }
19312f3073b5SPhilipp Schaad 
19322f3073b5SPhilipp Schaad   return Ret;
19332f3073b5SPhilipp Schaad }
19342f3073b5SPhilipp Schaad 
1935edb885cbSTobias Grosser Function *
1936edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1937edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
193832837fe3STobias Grosser   std::vector<Type *> Args;
193979f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
194032837fe3STobias Grosser 
19412f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
19422f3073b5SPhilipp Schaad 
194332837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
194432837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
194532837fe3STobias Grosser       continue;
194632837fe3STobias Grosser 
1947fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1948fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1949206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1950fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
19512f3073b5SPhilipp Schaad       MemoryType.push_back(
19522f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1953fe74a7a1STobias Grosser     } else {
1954d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1955d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
19562f3073b5SPhilipp Schaad       MemoryType.push_back(
19572f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
195832837fe3STobias Grosser     }
1959fe74a7a1STobias Grosser   }
196032837fe3STobias Grosser 
1961f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1962f6044bd0STobias Grosser 
19632f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1964f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
19652f3073b5SPhilipp Schaad     MemoryType.push_back(
19662f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19672f3073b5SPhilipp Schaad   }
1968f6044bd0STobias Grosser 
1969c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1970c84a1995STobias Grosser 
1971cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1972cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1973cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1974cf66ef26STobias Grosser     isl_id_free(Id);
1975cf66ef26STobias Grosser     Args.push_back(Val->getType());
19762f3073b5SPhilipp Schaad     MemoryType.push_back(
19772f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1978cf66ef26STobias Grosser   }
1979c84a1995STobias Grosser 
19802f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1981edb885cbSTobias Grosser     Args.push_back(V->getType());
19822f3073b5SPhilipp Schaad     MemoryType.push_back(
19832f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19842f3073b5SPhilipp Schaad   }
1985edb885cbSTobias Grosser 
198632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
198732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
198832837fe3STobias Grosser                               GPUModule.get());
198917f01968SSiddharth Bhat 
19902f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
19912f3073b5SPhilipp Schaad 
19922f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
19932f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
19942f3073b5SPhilipp Schaad   }
19952f3073b5SPhilipp Schaad 
19962f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
19972f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
19982f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
19992f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
20002f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20012f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
20022f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20032f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
20042f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20052f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
20062f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20072f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
20082f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20092f3073b5SPhilipp Schaad   }
20102f3073b5SPhilipp Schaad 
201117f01968SSiddharth Bhat   switch (Arch) {
201217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
201332837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
201417f01968SSiddharth Bhat     break;
20152f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20162f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20172f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
20182f3073b5SPhilipp Schaad     break;
201917f01968SSiddharth Bhat   }
202032837fe3STobias Grosser 
202132837fe3STobias Grosser   auto Arg = FN->arg_begin();
202232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
202332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
202432837fe3STobias Grosser       continue;
202532837fe3STobias Grosser 
2026edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
2027edb885cbSTobias Grosser 
2028edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2029718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2030edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
2031edb885cbSTobias Grosser     Value *Val = &*Arg;
2032edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2033edb885cbSTobias Grosser     isl_ast_build *Build =
2034edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
2035f5aff704SRoman Gareev     Sizes.push_back(nullptr);
20363044dc51SMichael Kruse     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2037edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
20389e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2039edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
2040edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
2041edb885cbSTobias Grosser     }
2042edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
20434d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
204474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
2045edb885cbSTobias Grosser 
2046edb885cbSTobias Grosser     isl_ast_build_free(Build);
2047b513b491STobias Grosser     KernelIds.push_back(Id);
2048edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
204932837fe3STobias Grosser     Arg++;
205032837fe3STobias Grosser   }
205132837fe3STobias Grosser 
2052f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
2053f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2054f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
2055f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
2056f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2057f6044bd0STobias Grosser     Arg++;
2058f6044bd0STobias Grosser   }
2059f6044bd0STobias Grosser 
2060c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
2061c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2062c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
206312453403STobias Grosser     Value *Val = IDToValue[Id];
206412453403STobias Grosser     ValueMap[Val] = &*Arg;
2065c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
2066c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2067c84a1995STobias Grosser     Arg++;
2068c84a1995STobias Grosser   }
2069c84a1995STobias Grosser 
2070edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
2071edb885cbSTobias Grosser     Arg->setName(V->getName());
2072edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
2073edb885cbSTobias Grosser     Arg++;
2074edb885cbSTobias Grosser   }
2075edb885cbSTobias Grosser 
207632837fe3STobias Grosser   return FN;
207732837fe3STobias Grosser }
207832837fe3STobias Grosser 
2079472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
208017f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
208117f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
2082472f9654STobias Grosser 
208317f01968SSiddharth Bhat   switch (Arch) {
20842f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20852f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20862f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
208717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
208817f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
208917f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
209017f01968SSiddharth Bhat 
209117f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
209217f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
209317f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
209417f01968SSiddharth Bhat     break;
209517f01968SSiddharth Bhat   }
2096472f9654STobias Grosser 
2097472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2098472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
2099472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2100472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2101472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2102472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2103472f9654STobias Grosser     IDToValue[Id] = Val;
2104472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2105472f9654STobias Grosser   };
2106472f9654STobias Grosser 
2107472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2108472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2109472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2110472f9654STobias Grosser   }
2111472f9654STobias Grosser 
2112472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2113472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2114472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2115472f9654STobias Grosser   }
2116472f9654STobias Grosser }
2117472f9654STobias Grosser 
2118d71493cbSPhilip Pfaffe void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2119d71493cbSPhilip Pfaffe                                            bool SizeTypeIs64bit) {
21202f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
21212f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
21222f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
21232f3073b5SPhilipp Schaad 
21242f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
21252f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
21262f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
2127d71493cbSPhilip Pfaffe   IntegerType *SizeT =
2128d71493cbSPhilip Pfaffe       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
21292f3073b5SPhilipp Schaad 
2130d71493cbSPhilip Pfaffe   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2131d71493cbSPhilip Pfaffe                            IntegerType *SizeT) mutable {
21322f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21332f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
21342f3073b5SPhilipp Schaad 
21352f3073b5SPhilipp Schaad     // If FN is not available, declare it.
21362f3073b5SPhilipp Schaad     if (!FN) {
21372f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
21382f3073b5SPhilipp Schaad       std::vector<Type *> Args;
2139d71493cbSPhilip Pfaffe       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
21402f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
21412f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
21422f3073b5SPhilipp Schaad     }
21432f3073b5SPhilipp Schaad 
21442f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
2145d71493cbSPhilip Pfaffe     if (SizeT == Builder.getInt32Ty())
21462f3073b5SPhilipp Schaad       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
21472f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
21482f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
21492f3073b5SPhilipp Schaad   };
21502f3073b5SPhilipp Schaad 
21512f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
2152d71493cbSPhilip Pfaffe     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
21532f3073b5SPhilipp Schaad 
21542f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
2155d71493cbSPhilip Pfaffe     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
21562f3073b5SPhilipp Schaad }
21572f3073b5SPhilipp Schaad 
215800bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
215900bb5a99STobias Grosser   auto Arg = FN->arg_begin();
216000bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
216100bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
216200bb5a99STobias Grosser       continue;
216300bb5a99STobias Grosser 
216400bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2165718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
216600bb5a99STobias Grosser     isl_id_free(Id);
216700bb5a99STobias Grosser 
216800bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
216900bb5a99STobias Grosser       Arg++;
217000bb5a99STobias Grosser       continue;
217100bb5a99STobias Grosser     }
217200bb5a99STobias Grosser 
2173fe74a7a1STobias Grosser     Value *Val = &*Arg;
2174fe74a7a1STobias Grosser 
2175fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
217600bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2177fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
21789c486eb3SMichael Kruse       Val = Builder.CreateLoad(SAI->getElementType(), TypedArgPtr);
2179fe74a7a1STobias Grosser     }
2180fe74a7a1STobias Grosser 
2181fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
218200bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
218300bb5a99STobias Grosser 
218400bb5a99STobias Grosser     Arg++;
218500bb5a99STobias Grosser   }
218600bb5a99STobias Grosser }
218700bb5a99STobias Grosser 
218851dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
218951dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
219051dfc275STobias Grosser   auto Arg = FN->arg_begin();
219151dfc275STobias Grosser 
219251dfc275STobias Grosser   bool StoredScalar = false;
219351dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
219451dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
219551dfc275STobias Grosser       continue;
219651dfc275STobias Grosser 
219751dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2198718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
219951dfc275STobias Grosser     isl_id_free(Id);
220051dfc275STobias Grosser 
220151dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
220251dfc275STobias Grosser       Arg++;
220351dfc275STobias Grosser       continue;
220451dfc275STobias Grosser     }
220551dfc275STobias Grosser 
220651dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
220751dfc275STobias Grosser       Arg++;
220851dfc275STobias Grosser       continue;
220951dfc275STobias Grosser     }
221051dfc275STobias Grosser 
221151dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
221251dfc275STobias Grosser     Value *ArgPtr = &*Arg;
221351dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
221451dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
22159c486eb3SMichael Kruse     Value *Val = Builder.CreateLoad(SAI->getElementType(), Alloca);
221651dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
221751dfc275STobias Grosser     StoredScalar = true;
221851dfc275STobias Grosser 
221951dfc275STobias Grosser     Arg++;
222051dfc275STobias Grosser   }
222151dfc275STobias Grosser 
2222638316daSSiddharth Bhat   if (StoredScalar) {
222351dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
222451dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
222551dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
222651dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2227638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
222851dfc275STobias Grosser       BuildSuccessful = 0;
2229349506a9SNicola Zaghen       LLVM_DEBUG(
2230638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2231638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2232638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2233638316daSSiddharth Bhat     }
2234638316daSSiddharth Bhat   }
223551dfc275STobias Grosser }
223651dfc275STobias Grosser 
2237b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2238b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2239b513b491STobias Grosser 
2240b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2241b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2242b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2243206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2244b513b491STobias Grosser 
2245f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2246b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2247b513b491STobias Grosser 
2248f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2249928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2250b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2251f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2252b513b491STobias Grosser       isl_val_free(Val);
2253b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2254928d7573STobias Grosser     }
2255928d7573STobias Grosser 
2256928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2257928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2258928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2259928d7573STobias Grosser       isl_val_free(Val);
2260b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2261b513b491STobias Grosser     }
2262b513b491STobias Grosser 
2263130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2264130ca30fSTobias Grosser     Value *Allocation;
2265130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2266130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2267130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2268130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2269f7b3ae65SMichael Kruse       GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8));
2270f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2271f919d8b3STobias Grosser 
2272130ca30fSTobias Grosser       Allocation = GlobalVar;
2273130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2274130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2275130ca30fSTobias Grosser     } else {
2276130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2277130ca30fSTobias Grosser     }
22784d5a9172STobias Grosser     SAI =
22794d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
228000fd43b3SPhilip Pfaffe     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2281130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2282130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2283b513b491STobias Grosser     KernelIds.push_back(Id);
2284b513b491STobias Grosser     IDToSAI[Id] = SAI;
2285b513b491STobias Grosser   }
2286b513b491STobias Grosser }
2287b513b491STobias Grosser 
2288f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2289f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2290f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
229179f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
229232837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
229317f01968SSiddharth Bhat 
229417f01968SSiddharth Bhat   switch (Arch) {
229517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
229617f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
229732837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
229817f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
229917f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
230032837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
230117f01968SSiddharth Bhat     break;
23022f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23032f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
23042f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
23052f3073b5SPhilipp Schaad     break;
23062f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23072f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
23082f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
23092f3073b5SPhilipp Schaad     break;
231017f01968SSiddharth Bhat   }
231132837fe3STobias Grosser 
2312edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
231332837fe3STobias Grosser 
231459ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
231532837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
231632837fe3STobias Grosser 
231759ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
231859ab0705STobias Grosser 
231932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
232032837fe3STobias Grosser   Builder.CreateRetVoid();
232132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2322472f9654STobias Grosser 
2323629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2324629109b6STobias Grosser 
232500bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2326b513b491STobias Grosser   createKernelVariables(Kernel, FN);
23272f3073b5SPhilipp Schaad 
23282f3073b5SPhilipp Schaad   switch (Arch) {
23292f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2330472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
23312f3073b5SPhilipp Schaad     break;
23322f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
2333d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, false);
2334d71493cbSPhilip Pfaffe     break;
23352f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
2336d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, true);
23372f3073b5SPhilipp Schaad     break;
23382f3073b5SPhilipp Schaad   }
233932837fe3STobias Grosser }
234032837fe3STobias Grosser 
234174dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
234217f01968SSiddharth Bhat   llvm::Triple GPUTriple;
234317f01968SSiddharth Bhat 
234417f01968SSiddharth Bhat   switch (Arch) {
234517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
234617f01968SSiddharth Bhat     switch (Runtime) {
234717f01968SSiddharth Bhat     case GPURuntime::CUDA:
234817f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
234917f01968SSiddharth Bhat       break;
235017f01968SSiddharth Bhat     case GPURuntime::OpenCL:
235117f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
235217f01968SSiddharth Bhat       break;
235317f01968SSiddharth Bhat     }
235417f01968SSiddharth Bhat     break;
23552f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23562f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23572f3073b5SPhilipp Schaad     std::string SPIRAssembly;
23582f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
23592f3073b5SPhilipp Schaad     IROstream << *GPUModule;
23602f3073b5SPhilipp Schaad     IROstream.flush();
23612f3073b5SPhilipp Schaad     return SPIRAssembly;
236217f01968SSiddharth Bhat   }
236317f01968SSiddharth Bhat 
236474dc3cb4STobias Grosser   std::string ErrMsg;
236574dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
236674dc3cb4STobias Grosser 
236774dc3cb4STobias Grosser   if (!GPUTarget) {
236874dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
236974dc3cb4STobias Grosser     return "";
237074dc3cb4STobias Grosser   }
237174dc3cb4STobias Grosser 
237274dc3cb4STobias Grosser   TargetOptions Options;
237374dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
237417f01968SSiddharth Bhat 
237517f01968SSiddharth Bhat   std::string subtarget;
237617f01968SSiddharth Bhat 
237717f01968SSiddharth Bhat   switch (Arch) {
237817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
237917f01968SSiddharth Bhat     subtarget = CudaVersion;
238017f01968SSiddharth Bhat     break;
23812f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23822f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23832f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
238417f01968SSiddharth Bhat   }
238517f01968SSiddharth Bhat 
238617f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
238717f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
238874dc3cb4STobias Grosser 
238974dc3cb4STobias Grosser   SmallString<0> ASMString;
239074dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
239174dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
239274dc3cb4STobias Grosser 
239374dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
239474dc3cb4STobias Grosser 
23951dfede31SReid Kleckner   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile,
23969a45114bSPeter Collingbourne                                    true /* verify */)) {
239774dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
239874dc3cb4STobias Grosser     return "";
239974dc3cb4STobias Grosser   }
240074dc3cb4STobias Grosser 
240174dc3cb4STobias Grosser   PM.run(*GPUModule);
240274dc3cb4STobias Grosser 
24031a53b732SMichael Kruse   return ASMStream.str().str();
240474dc3cb4STobias Grosser }
240574dc3cb4STobias Grosser 
24068fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
24075b307cdbSTobias Grosser   bool RequiresLibDevice = false;
24088fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
24098fc6cdfbSTobias Grosser     if (!F.isDeclaration())
24108fc6cdfbSTobias Grosser       continue;
24118fc6cdfbSTobias Grosser 
241266a05ad6SPhilip Pfaffe     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
24138fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
241456572c6aSSiddharth Bhat       // We need to handle the case where a module looks like this:
241556572c6aSSiddharth Bhat       // @expf(..)
241656572c6aSSiddharth Bhat       // @llvm.exp.f64(..)
241756572c6aSSiddharth Bhat       // Both of these functions would be renamed to `__nv_expf`.
241856572c6aSSiddharth Bhat       //
241956572c6aSSiddharth Bhat       // So, we must first check for the existence of the libdevice function.
242056572c6aSSiddharth Bhat       // If this exists, we replace our current function with it.
242156572c6aSSiddharth Bhat       //
242256572c6aSSiddharth Bhat       // If it does not exist, we rename the current function to the
242356572c6aSSiddharth Bhat       // libdevice functiono name.
242456572c6aSSiddharth Bhat       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
242556572c6aSSiddharth Bhat         F.replaceAllUsesWith(Replacement);
242656572c6aSSiddharth Bhat       else
24278fc6cdfbSTobias Grosser         F.setName(CUDALibDeviceFunc);
24285b307cdbSTobias Grosser       RequiresLibDevice = true;
24298fc6cdfbSTobias Grosser     }
24308fc6cdfbSTobias Grosser   }
24318fc6cdfbSTobias Grosser 
24325b307cdbSTobias Grosser   return RequiresLibDevice;
24338fc6cdfbSTobias Grosser }
24348fc6cdfbSTobias Grosser 
24358fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
24368fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
24378fc6cdfbSTobias Grosser     return;
24388fc6cdfbSTobias Grosser 
24398fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
24408fc6cdfbSTobias Grosser     SMDiagnostic Error;
24418fc6cdfbSTobias Grosser 
24428fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
24438fc6cdfbSTobias Grosser     auto LibDeviceModule =
24448fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
24458fc6cdfbSTobias Grosser 
24468fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
24478fc6cdfbSTobias Grosser       BuildSuccessful = false;
24488fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
24498fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
24508fc6cdfbSTobias Grosser                          "accordingly.\n");
24518fc6cdfbSTobias Grosser       return;
24528fc6cdfbSTobias Grosser     }
24538fc6cdfbSTobias Grosser 
24548fc6cdfbSTobias Grosser     Linker L(*GPUModule);
24558fc6cdfbSTobias Grosser 
24568fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
24578fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
24588fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
24598fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
24608fc6cdfbSTobias Grosser   }
24618fc6cdfbSTobias Grosser }
24628fc6cdfbSTobias Grosser 
246357793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
246465d7f72fSSiddharth Bhat 
24655857b701STobias Grosser   if (verifyModule(*GPUModule)) {
2466349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
246765d7f72fSSiddharth Bhat                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2468349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2469a0fb8b23SSiddharth Bhat                verifyModule(*GPUModule, &dbgs()););
247065d7f72fSSiddharth Bhat 
247165d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
247265d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
247365d7f72fSSiddharth Bhat 
24745857b701STobias Grosser     BuildSuccessful = false;
24755857b701STobias Grosser     return "";
24765857b701STobias Grosser   }
247732837fe3STobias Grosser 
24788fc6cdfbSTobias Grosser   addCUDALibDevice();
24798fc6cdfbSTobias Grosser 
248032837fe3STobias Grosser   if (DumpKernelIR)
248132837fe3STobias Grosser     outs() << *GPUModule << "\n";
248232837fe3STobias Grosser 
24832f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
24849a18d559STobias Grosser     // Optimize module.
24859a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
24869a18d559STobias Grosser     PassManagerBuilder PassBuilder;
24879a18d559STobias Grosser     PassBuilder.OptLevel = 3;
24889a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
24899a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
24909a18d559STobias Grosser     OptPasses.run(*GPUModule);
24912f3073b5SPhilipp Schaad   }
24929a18d559STobias Grosser 
249374dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
249474dc3cb4STobias Grosser 
249574dc3cb4STobias Grosser   if (DumpKernelASM)
249674dc3cb4STobias Grosser     outs() << Assembly << "\n";
249774dc3cb4STobias Grosser 
249832837fe3STobias Grosser   GPUModule.release();
2499472f9654STobias Grosser   KernelIDs.clear();
250057793596STobias Grosser 
250157793596STobias Grosser   return Assembly;
250232837fe3STobias Grosser }
2503eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2504eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2505eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2506eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2507eadf76d3SSiddharth Bhat ///
2508eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2509eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2510eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2511eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2512eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2513eadf76d3SSiddharth Bhat 
2514eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2515eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2516eadf76d3SSiddharth Bhat   }
2517eadf76d3SSiddharth Bhat   return List;
2518eadf76d3SSiddharth Bhat }
2519eadf76d3SSiddharth Bhat 
2520eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2521eadf76d3SSiddharth Bhat ///
2522eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2523eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2524eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2525eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2526eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2527eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2528eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2529eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2530eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2531eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2532eadf76d3SSiddharth Bhat ///                  affines.
2533eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2534eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2535eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2536eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2537eadf76d3SSiddharth Bhat 
2538eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2539eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2540eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2541eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2542eadf76d3SSiddharth Bhat   }
2543eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2544eadf76d3SSiddharth Bhat 
2545eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2546eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2547eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2548eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2549eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2550eadf76d3SSiddharth Bhat   }
2551eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2552eadf76d3SSiddharth Bhat }
255332837fe3STobias Grosser 
25549dfe4e7cSTobias Grosser namespace {
2555bd93df93SMichael Kruse class PPCGCodeGeneration final : public ScopPass {
25569dfe4e7cSTobias Grosser public:
25579dfe4e7cSTobias Grosser   static char ID;
25589dfe4e7cSTobias Grosser 
255917f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
256017f01968SSiddharth Bhat 
256117f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
256217f01968SSiddharth Bhat 
2563e938517eSTobias Grosser   /// The scop that is currently processed.
2564e938517eSTobias Grosser   Scop *S;
2565e938517eSTobias Grosser 
256638fc0aedSTobias Grosser   LoopInfo *LI;
256738fc0aedSTobias Grosser   DominatorTree *DT;
256838fc0aedSTobias Grosser   ScalarEvolution *SE;
256938fc0aedSTobias Grosser   const DataLayout *DL;
257038fc0aedSTobias Grosser   RegionInfo *RI;
257138fc0aedSTobias Grosser 
25723dcb5351SMichael Kruse   PPCGCodeGeneration() : ScopPass(ID) {
25733dcb5351SMichael Kruse     // Apply defaults.
25743dcb5351SMichael Kruse     Runtime = GPURuntimeChoice;
25753dcb5351SMichael Kruse     Architecture = GPUArchChoice;
25763dcb5351SMichael Kruse   }
25779dfe4e7cSTobias Grosser 
2578e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2579e938517eSTobias Grosser   ///
2580e938517eSTobias Grosser   /// @returns The compilation options.
2581e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2582e938517eSTobias Grosser     auto DebugOptions =
2583e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2584e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2585e938517eSTobias Grosser 
2586e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2587e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2588e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2589e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
25908950ceadSTobias Grosser     DebugOptions->verbose = false;
2591e938517eSTobias Grosser 
2592e938517eSTobias Grosser     Options->debug = DebugOptions;
2593e938517eSTobias Grosser 
25949e3db2b7SSiddharth Bhat     Options->group_chains = false;
2595e938517eSTobias Grosser     Options->reschedule = true;
2596e938517eSTobias Grosser     Options->scale_tile_loops = false;
2597e938517eSTobias Grosser     Options->wrap = false;
2598e938517eSTobias Grosser 
2599e938517eSTobias Grosser     Options->non_negative_parameters = false;
2600e938517eSTobias Grosser     Options->ctx = nullptr;
2601e938517eSTobias Grosser     Options->sizes = nullptr;
2602e938517eSTobias Grosser 
26039e3db2b7SSiddharth Bhat     Options->tile = true;
26044eaedde5STobias Grosser     Options->tile_size = 32;
26054eaedde5STobias Grosser 
26069e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
26079e3db2b7SSiddharth Bhat 
2608130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2609b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2610b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2611e938517eSTobias Grosser 
2612e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2613e938517eSTobias Grosser     Options->openmp = false;
2614e938517eSTobias Grosser     Options->linearize_device_arrays = true;
26159e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2616e938517eSTobias Grosser 
26179e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
26189e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
26199e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26209e3db2b7SSiddharth Bhat 
26219e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26229e3db2b7SSiddharth Bhat     Options->hybrid = false;
2623e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2624e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2625e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2626e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2627e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2628e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2629e938517eSTobias Grosser 
2630e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2631e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2632e938517eSTobias Grosser 
2633e938517eSTobias Grosser     return Options;
2634e938517eSTobias Grosser   }
2635e938517eSTobias Grosser 
2636f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2637f384594dSTobias Grosser   ///
2638f384594dSTobias Grosser   /// Instead of a normal access of the form:
2639f384594dSTobias Grosser   ///
2640f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2641f384594dSTobias Grosser   ///
2642f384594dSTobias Grosser   /// a tagged access has the form
2643f384594dSTobias Grosser   ///
2644f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2645f384594dSTobias Grosser   ///
2646f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2647f384594dSTobias Grosser   /// triggered the access.
2648f384594dSTobias Grosser   ///
2649f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2650f384594dSTobias Grosser   ///
2651f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2652f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2653b65ccc43STobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2654f384594dSTobias Grosser 
2655f384594dSTobias Grosser     for (auto &Stmt : *S)
2656f384594dSTobias Grosser       for (auto &Acc : Stmt)
2657f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
26581515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2659dcf8d696STobias Grosser           Relation =
2660dcf8d696STobias Grosser               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2661f384594dSTobias Grosser 
2662f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2663f384594dSTobias Grosser           Space = isl_space_range(Space);
2664f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2665fe46c3ffSTobias Grosser           Space =
2666fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2667f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2668f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2669f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2670f384594dSTobias Grosser         }
2671f384594dSTobias Grosser 
2672f384594dSTobias Grosser     return Accesses;
2673f384594dSTobias Grosser   }
2674f384594dSTobias Grosser 
2675f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2676f384594dSTobias Grosser   ///
2677f384594dSTobias Grosser   /// @see getTaggedAccesses
2678f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2679f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2680f384594dSTobias Grosser   }
2681f384594dSTobias Grosser 
2682f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2683f384594dSTobias Grosser   ///
2684f384594dSTobias Grosser   /// @see getTaggedAccesses
2685f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2686f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2687f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2688f384594dSTobias Grosser   }
2689f384594dSTobias Grosser 
2690f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2691f384594dSTobias Grosser   ///
2692f384594dSTobias Grosser   /// @see getTaggedAccesses
2693f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2694f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2695f384594dSTobias Grosser   }
2696f384594dSTobias Grosser 
2697aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2698aef5196fSTobias Grosser   ///
2699aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2700aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2701aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2702aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2703aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2704aef5196fSTobias Grosser   /// the data format that ppcg expects.
2705aef5196fSTobias Grosser   ///
2706aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2707aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2708aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
270900fd43b3SPhilip Pfaffe         S->getIslCtx().get(),
2710bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
271100fd43b3SPhilip Pfaffe     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2712aef5196fSTobias Grosser 
271325271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
27149a63570bSTobias Grosser       isl_id *Id = S->getIdForParam(P).release();
2715aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2716aef5196fSTobias Grosser     }
2717aef5196fSTobias Grosser 
2718aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
271977eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2720aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2721aef5196fSTobias Grosser     }
2722aef5196fSTobias Grosser 
2723aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2724aef5196fSTobias Grosser 
2725aef5196fSTobias Grosser     return Names;
2726aef5196fSTobias Grosser   }
2727aef5196fSTobias Grosser 
2728e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2729e938517eSTobias Grosser   ///
2730f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2731f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2732f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2733f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2734e938517eSTobias Grosser   ///
2735e938517eSTobias Grosser   /// @returns A new ppcg scop.
2736e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
27379e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
27389e3db2b7SSiddharth Bhat 
2739e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2740e938517eSTobias Grosser 
2741e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2742a82f2d26SSiddharth Bhat     // enable live range reordering
2743a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2744e938517eSTobias Grosser 
2745e938517eSTobias Grosser     PPCGScop->start = 0;
2746e938517eSTobias Grosser     PPCGScop->end = 0;
2747e938517eSTobias Grosser 
27488ea1fc19STobias Grosser     PPCGScop->context = S->getContext().release();
274931df6f31STobias Grosser     PPCGScop->domain = S->getDomains().release();
27509e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
27518ea1fc19STobias Grosser     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2752f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
27535ab39ff2STobias Grosser     PPCGScop->reads = S->getReads().release();
2754e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2755f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
27565ab39ff2STobias Grosser     PPCGScop->may_writes = S->getWrites().release();
2757f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
27585ab39ff2STobias Grosser     PPCGScop->must_writes = S->getMustWrites().release();
2759e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
27608dae41a1STobias Grosser     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
27618dae41a1STobias Grosser     PPCGScop->must_kills = KillsInfo.MustKills.release();
27629e3db2b7SSiddharth Bhat 
2763e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2764a82f2d26SSiddharth Bhat     PPCGScop->independence =
2765a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2766e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2767e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2768e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2769e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2770e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2771e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2772e938517eSTobias Grosser 
277361bd3a48STobias Grosser     PPCGScop->schedule = S->getScheduleTree().release();
2774a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2775a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2776a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
27778dae41a1STobias Grosser           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2778a82f2d26SSiddharth Bhat 
2779a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2780e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2781e938517eSTobias Grosser 
2782f384594dSTobias Grosser     compute_tagger(PPCGScop);
2783f384594dSTobias Grosser     compute_dependences(PPCGScop);
27849e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2785f384594dSTobias Grosser 
2786e938517eSTobias Grosser     return PPCGScop;
2787e938517eSTobias Grosser   }
2788e938517eSTobias Grosser 
2789a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
279060f63b49STobias Grosser   ///
279160f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
279260f63b49STobias Grosser   ///
279360f63b49STobias Grosser   /// @returns A list of array accesses.
279460f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
279560f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
279660f63b49STobias Grosser 
279760f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
279800fd43b3SPhilip Pfaffe       auto Access =
279900fd43b3SPhilip Pfaffe           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
280060f63b49STobias Grosser       Access->read = Acc->isRead();
280160f63b49STobias Grosser       Access->write = Acc->isWrite();
28021515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
280360f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
280460f63b49STobias Grosser       Space = isl_space_range(Space);
280560f63b49STobias Grosser       Space = isl_space_from_range(Space);
2806fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
280760f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
280860f63b49STobias Grosser       Access->tagged_access =
28091515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2810b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2811fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
281260f63b49STobias Grosser       Access->next = Accesses;
2813b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2814ecb94a03STobias Grosser       // TODO: Also mark one-element accesses to arrays as fixed-element.
2815ecb94a03STobias Grosser       Access->fixed_element =
2816ecb94a03STobias Grosser           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
281760f63b49STobias Grosser       Accesses = Access;
281860f63b49STobias Grosser     }
281960f63b49STobias Grosser 
282060f63b49STobias Grosser     return Accesses;
282160f63b49STobias Grosser   }
282260f63b49STobias Grosser 
282369b46751STobias Grosser   /// Collect the list of GPU statements.
282469b46751STobias Grosser   ///
282569b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
282669b46751STobias Grosser   /// as well as a list with all memory accesses.
282769b46751STobias Grosser   ///
282869b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
282969b46751STobias Grosser   ///
283069b46751STobias Grosser   /// @returns A linked-list of statements.
283169b46751STobias Grosser   gpu_stmt *getStatements() {
283200fd43b3SPhilip Pfaffe     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
283369b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
283469b46751STobias Grosser 
283569b46751STobias Grosser     int i = 0;
283669b46751STobias Grosser     for (auto &Stmt : *S) {
283769b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
283869b46751STobias Grosser 
2839dcf8d696STobias Grosser       GPUStmt->id = Stmt.getDomainId().release();
284069b46751STobias Grosser 
284169b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
284269b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
284360f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
284469b46751STobias Grosser       i++;
284569b46751STobias Grosser     }
284669b46751STobias Grosser 
284769b46751STobias Grosser     return Stmts;
284869b46751STobias Grosser   }
284969b46751STobias Grosser 
285060f63b49STobias Grosser   /// Derive the extent of an array.
285160f63b49STobias Grosser   ///
2852d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2853d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2854d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2855d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2856d58acf86STobias Grosser   /// subscript value for the first dimension.
285760f63b49STobias Grosser   ///
285860f63b49STobias Grosser   /// @param Array The array to derive the extent for.
285960f63b49STobias Grosser   ///
286060f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
2861d2e57981STobias Grosser   isl::set getExtent(ScopArrayInfo *Array) {
2862d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
2863fa03cb76STobias Grosser 
2864fa03cb76STobias Grosser     if (Array->getNumberOfDimensions() == 0)
2865fa03cb76STobias Grosser       return isl::set::universe(Array->getSpace());
2866fa03cb76STobias Grosser 
2867fa03cb76STobias Grosser     isl::union_map Accesses = S->getAccesses(Array);
2868d2e57981STobias Grosser     isl::union_set AccessUSet = Accesses.range();
2869d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2870d2e57981STobias Grosser     AccessUSet = AccessUSet.detect_equalities();
2871d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2872d58acf86STobias Grosser 
2873d2e57981STobias Grosser     if (AccessUSet.is_empty())
2874d2e57981STobias Grosser       return isl::set::empty(Array->getSpace());
2875d58acf86STobias Grosser 
2876d2e57981STobias Grosser     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
287760f63b49STobias Grosser 
2878d2e57981STobias Grosser     isl::local_space LS = isl::local_space(Array->getSpace());
2879d58acf86STobias Grosser 
2880d2e57981STobias Grosser     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2881d2e57981STobias Grosser     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2882d2e57981STobias Grosser     isl::pw_aff OuterMax = AccessSet.dim_max(0);
288344596fe6SRiccardo Mori     OuterMin = OuterMin.add_dims(isl::dim::in,
288444596fe6SRiccardo Mori                                  unsignedFromIslSize(Val.dim(isl::dim::in)));
288544596fe6SRiccardo Mori     OuterMax = OuterMax.add_dims(isl::dim::in,
288644596fe6SRiccardo Mori                                  unsignedFromIslSize(Val.dim(isl::dim::in)));
2887d2e57981STobias Grosser     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2888d2e57981STobias Grosser     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2889d58acf86STobias Grosser 
2890d2e57981STobias Grosser     isl::set Extent = isl::set::universe(Array->getSpace());
2891d58acf86STobias Grosser 
2892d2e57981STobias Grosser     Extent = Extent.intersect(OuterMin.le_set(Val));
2893d2e57981STobias Grosser     Extent = Extent.intersect(OuterMax.ge_set(Val));
2894d58acf86STobias Grosser 
2895d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2896d2e57981STobias Grosser       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2897d58acf86STobias Grosser 
2898b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2899d2e57981STobias Grosser       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2900b7f68b8cSSiddharth Bhat 
2901b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2902b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2903d2e57981STobias Grosser       if (PwAff.is_null()) {
2904b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2905b7f68b8cSSiddharth Bhat         continue;
2906b7f68b8cSSiddharth Bhat       }
2907b7f68b8cSSiddharth Bhat 
2908d2e57981STobias Grosser       isl::pw_aff Val = isl::aff::var_on_domain(
2909d2e57981STobias Grosser           isl::local_space(Array->getSpace()), isl::dim::set, i);
291044596fe6SRiccardo Mori       PwAff = PwAff.add_dims(isl::dim::in,
291144596fe6SRiccardo Mori                              unsignedFromIslSize(Val.dim(isl::dim::in)));
2912d2e57981STobias Grosser       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2913d2e57981STobias Grosser       isl::set Set = PwAff.gt_set(Val);
2914d2e57981STobias Grosser       Extent = Set.intersect(Extent);
2915d58acf86STobias Grosser     }
2916d58acf86STobias Grosser 
2917d58acf86STobias Grosser     return Extent;
291860f63b49STobias Grosser   }
291960f63b49STobias Grosser 
292060f63b49STobias Grosser   /// Derive the bounds of an array.
292160f63b49STobias Grosser   ///
292260f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
292360f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
292460f63b49STobias Grosser   /// ScopArrayInfo.
292560f63b49STobias Grosser   ///
292660f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
292760f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
292860f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2929eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
29309e3db2b7SSiddharth Bhat 
293160f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
293202293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
293302293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
293402293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
293502293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
293602293ed7STobias Grosser         isl_set_free(Dom);
29379e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2938eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
293902293ed7STobias Grosser       } else {
294060f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
294160f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
294260f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
294360f63b49STobias Grosser         isl_set_free(Dom);
294460f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
294502293ed7STobias Grosser         isl_local_space *LS =
294602293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
294760f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
294860f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
294960f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
29508ea1fc19STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2951eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
295260f63b49STobias Grosser       }
295302293ed7STobias Grosser     }
295460f63b49STobias Grosser 
295560f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
295677eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
295760f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
295860f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
2959e2950f46SSiddharth Bhat 
2960e2950f46SSiddharth Bhat       // We need types to work out, which is why we perform this weird dance
2961e2950f46SSiddharth Bhat       // with `Aff` and `Bound`. Consider this example:
2962e2950f46SSiddharth Bhat 
2963e2950f46SSiddharth Bhat       // LS: [p] -> { [] }
2964e2950f46SSiddharth Bhat       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2965e2950f46SSiddharth Bhat       // This `~` is used to denote a "null space" (which is different from
2966e2950f46SSiddharth Bhat       // a *zero dimensional* space), which is something that ISL does not
2967e2950f46SSiddharth Bhat       // show you when pretty printing.
2968e2950f46SSiddharth Bhat 
2969e2950f46SSiddharth Bhat       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2970e2950f46SSiddharth Bhat       // space, not a "null space" which does not exist at all.
2971e2950f46SSiddharth Bhat 
2972e2950f46SSiddharth Bhat       // When we pullback (precompose) `Bound` with `Zero`, we get:
2973e2950f46SSiddharth Bhat       // Bound . Zero =
2974e2950f46SSiddharth Bhat       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2975e2950f46SSiddharth Bhat       //     [p] -> { ~ -> [(10p)] } =
2976e2950f46SSiddharth Bhat       //     [p] -> [(10p)] (as ISL pretty prints it)
2977e2950f46SSiddharth Bhat       // Bound Pullback: [p] -> { [(10p)] }
2978e2950f46SSiddharth Bhat 
2979e2950f46SSiddharth Bhat       // We want this kind of an expression for Bound, without a
2980e2950f46SSiddharth Bhat       // zero dimensional input, but with a "null space" input for the types
2981e2950f46SSiddharth Bhat       // to work out later on, as far as I (Siddharth Bhat) understand.
2982e2950f46SSiddharth Bhat       // I was unable to find a reference to this in the ISL manual.
2983e2950f46SSiddharth Bhat       // References: Tobias Grosser.
2984e2950f46SSiddharth Bhat 
298560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2986eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
298760f63b49STobias Grosser     }
29889e3db2b7SSiddharth Bhat 
2989eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2990eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2991eadf76d3SSiddharth Bhat     /// appropriate space.
2992eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2993eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2994eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2995eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2996b65ccc43STobias Grosser     isl_space *SeedAlignSpace = S->getParamSpace().release();
2997eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2998eadf76d3SSiddharth Bhat 
2999eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
3000eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
3001eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
3002eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
3003eadf76d3SSiddharth Bhat 
3004eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
3005eadf76d3SSiddharth Bhat 
3006eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
300700fd43b3SPhilip Pfaffe         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
3008eadf76d3SSiddharth Bhat 
30099e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
3010eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
30119e3db2b7SSiddharth Bhat 
30129e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
30139e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
30149e3db2b7SSiddharth Bhat 
30159e3db2b7SSiddharth Bhat     PPCGArray.bound =
30169e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
30179e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
301860f63b49STobias Grosser   }
301960f63b49STobias Grosser 
302060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
302160f63b49STobias Grosser   ///
302260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
302343f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
302443f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
302560f63b49STobias Grosser     int i = 0;
302643f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
302760f63b49STobias Grosser       std::string TypeName;
302860f63b49STobias Grosser       raw_string_ostream OS(TypeName);
302960f63b49STobias Grosser 
303060f63b49STobias Grosser       OS << *Array->getElementType();
303160f63b49STobias Grosser       TypeName = OS.str();
303260f63b49STobias Grosser 
303360f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
303460f63b49STobias Grosser 
303577eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
303660f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
303734eeabbcSSiddharth Bhat       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
303860f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
303960f63b49STobias Grosser       PPCGArray.extent = nullptr;
304060f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
3041d2e57981STobias Grosser       PPCGArray.extent = getExtent(Array).release();
304260f63b49STobias Grosser       PPCGArray.n_ref = 0;
304360f63b49STobias Grosser       PPCGArray.refs = nullptr;
304460f63b49STobias Grosser       PPCGArray.accessed = true;
3045fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
3046fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
304760f63b49STobias Grosser       PPCGArray.has_compound_element = false;
304860f63b49STobias Grosser       PPCGArray.local = false;
304960f63b49STobias Grosser       PPCGArray.declare_local = false;
305060f63b49STobias Grosser       PPCGArray.global = false;
305160f63b49STobias Grosser       PPCGArray.linearize = false;
305260f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
305313c78e4dSTobias Grosser       PPCGArray.user = Array;
305460f63b49STobias Grosser 
30559e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
305660f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
30572d010dafSTobias Grosser       i++;
3058b9fc860aSTobias Grosser 
3059b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
3060ecb94a03STobias Grosser       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
306160f63b49STobias Grosser     }
306260f63b49STobias Grosser   }
306360f63b49STobias Grosser 
306460f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
306560f63b49STobias Grosser   ///
306660f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
306760f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
3068b65ccc43STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
306960f63b49STobias Grosser 
3070d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
307177eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
307260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
307360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
307460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
307560f63b49STobias Grosser     }
307660f63b49STobias Grosser 
307760f63b49STobias Grosser     return Maps;
307860f63b49STobias Grosser   }
307960f63b49STobias Grosser 
3080e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
3081e938517eSTobias Grosser   ///
3082a6d48f59SMichael Kruse   /// @returns A new gpu program description.
3083e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3084e938517eSTobias Grosser 
3085e938517eSTobias Grosser     if (!PPCGScop)
3086e938517eSTobias Grosser       return nullptr;
3087e938517eSTobias Grosser 
308800fd43b3SPhilip Pfaffe     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3089e938517eSTobias Grosser 
309000fd43b3SPhilip Pfaffe     PPCGProg->ctx = S->getIslCtx().get();
3091e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
3092aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
309360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
309460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
309560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
309660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
309760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
309860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
309960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
31009e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
3101e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
310269b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
310369b46751STobias Grosser     PPCGProg->stmts = getStatements();
310443f178bbSSiddharth Bhat 
310543f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
310643f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
310743f178bbSSiddharth Bhat     // empty arrays:
310843f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
310943f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
311043f178bbSSiddharth Bhat     auto ValidSAIsRange =
311143f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3112d2e57981STobias Grosser           return !getExtent(SAI).is_empty();
311343f178bbSSiddharth Bhat         });
311443f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
311543f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
311643f178bbSSiddharth Bhat 
311743f178bbSSiddharth Bhat     PPCGProg->n_array =
311843f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
311958166b13SMichael Kruse     PPCGProg->array = isl_calloc_array(
312058166b13SMichael Kruse         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
312160f63b49STobias Grosser 
312243f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
3123e938517eSTobias Grosser 
3124ecb94a03STobias Grosser     PPCGProg->array_order = nullptr;
3125ecb94a03STobias Grosser     collect_order_dependences(PPCGProg);
3126ecb94a03STobias Grosser 
3127d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3128e938517eSTobias Grosser     return PPCGProg;
3129e938517eSTobias Grosser   }
3130e938517eSTobias Grosser 
313169b46751STobias Grosser   struct PrintGPUUserData {
313269b46751STobias Grosser     struct cuda_info *CudaInfo;
313369b46751STobias Grosser     struct gpu_prog *PPCGProg;
313469b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
313569b46751STobias Grosser   };
313669b46751STobias Grosser 
313769b46751STobias Grosser   /// Print a user statement node in the host code.
313869b46751STobias Grosser   ///
313969b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
314069b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
314169b46751STobias Grosser   /// host ast.
314269b46751STobias Grosser   ///
314369b46751STobias Grosser   /// @param P The printer to print to
314469b46751STobias Grosser   /// @param Options The printing options to use
314569b46751STobias Grosser   /// @param Node The node to print
314669b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
314769b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
314869b46751STobias Grosser   ///
314969b46751STobias Grosser   /// @returns A printer to which the output has been printed.
315069b46751STobias Grosser   static __isl_give isl_printer *
315169b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
315269b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
315369b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
315469b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
315569b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
315669b46751STobias Grosser 
315769b46751STobias Grosser     if (Id) {
315820251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
315920251734STobias Grosser 
316020251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
316120251734STobias Grosser       // otherwise try to call pet functionality that is not available in
316220251734STobias Grosser       // Polly.
316320251734STobias Grosser       if (IsUser) {
316420251734STobias Grosser         P = isl_printer_start_line(P);
316520251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
316620251734STobias Grosser         P = isl_printer_end_line(P);
316720251734STobias Grosser         isl_id_free(Id);
316820251734STobias Grosser         isl_ast_print_options_free(Options);
316920251734STobias Grosser         return P;
317020251734STobias Grosser       }
317120251734STobias Grosser 
317269b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
317369b46751STobias Grosser       isl_id_free(Id);
317469b46751STobias Grosser       Data->Kernels.push_back(Kernel);
317569b46751STobias Grosser     }
317669b46751STobias Grosser 
317769b46751STobias Grosser     return print_host_user(P, Options, Node, User);
317869b46751STobias Grosser   }
317969b46751STobias Grosser 
318069b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
318169b46751STobias Grosser   ///
318269b46751STobias Grosser   /// @param Kernel The kernel to print
318369b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
318400fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
318569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
318600fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
318769b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
318869b46751STobias Grosser     char *String = isl_printer_get_str(P);
3189936c74adSSiddharth Bhat     outs() << String << "\n";
319069b46751STobias Grosser     free(String);
319169b46751STobias Grosser     isl_printer_free(P);
319269b46751STobias Grosser   }
319369b46751STobias Grosser 
319469b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
319569b46751STobias Grosser   ///
319669b46751STobias Grosser   /// @param Tree An AST describing GPU code
319769b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
319869b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
319900fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
320069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
320169b46751STobias Grosser 
320269b46751STobias Grosser     PrintGPUUserData Data;
320369b46751STobias Grosser     Data.PPCGProg = PPCGProg;
320469b46751STobias Grosser 
320500fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
320669b46751STobias Grosser     Options =
320769b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
320869b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
320969b46751STobias Grosser     char *String = isl_printer_get_str(P);
3210936c74adSSiddharth Bhat     outs() << "# host\n";
3211936c74adSSiddharth Bhat     outs() << String << "\n";
321269b46751STobias Grosser     free(String);
321369b46751STobias Grosser     isl_printer_free(P);
321469b46751STobias Grosser 
321569b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
3216936c74adSSiddharth Bhat       outs() << "# kernel" << Kernel->id << "\n";
321769b46751STobias Grosser       printKernel(Kernel);
321869b46751STobias Grosser     }
321969b46751STobias Grosser   }
322069b46751STobias Grosser 
3221f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3222f384594dSTobias Grosser   //
3223f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3224f384594dSTobias Grosser   //
3225f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3226f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3227f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3228f384594dSTobias Grosser   //
3229f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3230f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3231f384594dSTobias Grosser   // strategy directly from this pass.
3232f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3233f384594dSTobias Grosser 
323400fd43b3SPhilip Pfaffe     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3235f384594dSTobias Grosser 
323600fd43b3SPhilip Pfaffe     PPCGGen->ctx = S->getIslCtx().get();
3237f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3238f384594dSTobias Grosser     PPCGGen->print = nullptr;
3239f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
324060c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3241f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3242f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3243f384594dSTobias Grosser     PPCGGen->types.n = 0;
3244f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3245f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3246f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3247f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3248f384594dSTobias Grosser 
3249f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
325007e7cb94SMichael Kruse     isl_options_set_schedule_serialize_sccs(PPCGGen->ctx, false);
3251f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3252f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
32532341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3254f384594dSTobias Grosser 
3255f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3256f384594dSTobias Grosser 
3257e32498c9STobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3258e32498c9STobias Grosser 
3259b5563c68STobias Grosser     Schedule =
3260b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3261b5563c68STobias Grosser 
326269b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3263aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3264349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3265638316daSSiddharth Bhat                         << " does not have permutable bands. Bailing out\n";);
326669b46751STobias Grosser     } else {
3267861a387fSTobias Grosser       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3268861a387fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
326969b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
327069b46751STobias Grosser     }
3271aef5196fSTobias Grosser 
3272f384594dSTobias Grosser     if (DumpSchedule) {
327300fd43b3SPhilip Pfaffe       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3274f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3275f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3276f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3277f384594dSTobias Grosser       if (Schedule)
3278f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3279f384594dSTobias Grosser       else
3280f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3281f384594dSTobias Grosser 
3282936c74adSSiddharth Bhat       outs() << isl_printer_get_str(P) << "\n";
3283f384594dSTobias Grosser       isl_printer_free(P);
3284f384594dSTobias Grosser     }
3285f384594dSTobias Grosser 
328669b46751STobias Grosser     if (DumpCode) {
3287936c74adSSiddharth Bhat       outs() << "Code\n";
3288936c74adSSiddharth Bhat       outs() << "====\n";
328969b46751STobias Grosser       if (PPCGGen->tree)
329069b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
329169b46751STobias Grosser       else
3292936c74adSSiddharth Bhat         outs() << "No code generated\n";
329369b46751STobias Grosser     }
329469b46751STobias Grosser 
3295f384594dSTobias Grosser     isl_schedule_free(Schedule);
3296f384594dSTobias Grosser 
3297f384594dSTobias Grosser     return PPCGGen;
3298f384594dSTobias Grosser   }
3299f384594dSTobias Grosser 
3300f384594dSTobias Grosser   /// Free gpu_gen structure.
3301f384594dSTobias Grosser   ///
3302f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3303f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3304f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3305f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3306f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3307f384594dSTobias Grosser     free(PPCGGen);
3308f384594dSTobias Grosser   }
3309f384594dSTobias Grosser 
3310b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3311b307ed4dSTobias Grosser   ///
3312b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3313b307ed4dSTobias Grosser   /// ourselves.
3314b307ed4dSTobias Grosser   ///
3315b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3316b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3317b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3318b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3319b307ed4dSTobias Grosser     free(PPCGScop->options);
3320b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3321b307ed4dSTobias Grosser   }
3322b307ed4dSTobias Grosser 
332382f2af35STobias Grosser   /// Approximate the number of points in the set.
332482f2af35STobias Grosser   ///
332582f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
332682f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
332782f2af35STobias Grosser   ///
332882f2af35STobias Grosser   /// @param Set   The set to count.
332982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
333082f2af35STobias Grosser   ///              expression.
333182f2af35STobias Grosser   ///
333282f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
333382f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
333482f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
333582f2af35STobias Grosser 
333682f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
333782f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
333882f2af35STobias Grosser 
333982f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
334082f2af35STobias Grosser     Space = isl_space_params(Space);
334182f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
334282f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
334382f2af35STobias Grosser 
33443044dc51SMichael Kruse     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
334582f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
334682f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
334782f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
334882f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
334982f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
335082f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
335182f2af35STobias Grosser     }
335282f2af35STobias Grosser 
335382f2af35STobias Grosser     isl_set_free(Set);
335482f2af35STobias Grosser     isl_pw_aff_free(OneAff);
335582f2af35STobias Grosser 
335682f2af35STobias Grosser     return Expr;
335782f2af35STobias Grosser   }
335882f2af35STobias Grosser 
335982f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
336082f2af35STobias Grosser   /// statement.
336182f2af35STobias Grosser   ///
336282f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
336382f2af35STobias Grosser   ///              instructions.
336482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
336582f2af35STobias Grosser   ///              expression.
336682f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
336782f2af35STobias Grosser   ///          by @p Stmt.
336882f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
336982f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
3370dcf8d696STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
337182f2af35STobias Grosser 
337282f2af35STobias Grosser     long InstCount = 0;
337382f2af35STobias Grosser 
337482f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
337582f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
337682f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
337782f2af35STobias Grosser     } else {
337882f2af35STobias Grosser       auto *R = Stmt.getRegion();
337982f2af35STobias Grosser 
338082f2af35STobias Grosser       for (auto *BB : R->blocks()) {
338182f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
338282f2af35STobias Grosser       }
338382f2af35STobias Grosser     }
338482f2af35STobias Grosser 
338500fd43b3SPhilip Pfaffe     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
338682f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
338782f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
338882f2af35STobias Grosser   }
338982f2af35STobias Grosser 
339082f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
339182f2af35STobias Grosser   ///
339282f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
339382f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
339482f2af35STobias Grosser   ///              expression.
339582f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
339682f2af35STobias Grosser   ///          in @p S.
339782f2af35STobias Grosser   __isl_give isl_ast_expr *
339882f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
339982f2af35STobias Grosser     isl_ast_expr *Instructions;
340082f2af35STobias Grosser 
340100fd43b3SPhilip Pfaffe     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
340282f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
340382f2af35STobias Grosser 
340482f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
340582f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
340682f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
340782f2af35STobias Grosser     }
340882f2af35STobias Grosser     return Instructions;
340982f2af35STobias Grosser   }
341082f2af35STobias Grosser 
341182f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
341282f2af35STobias Grosser   ///
341382f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
341482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
341582f2af35STobias Grosser   ///              expression.
341682f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
341782f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
341882f2af35STobias Grosser   __isl_give isl_ast_expr *
341982f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
342082f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
342100fd43b3SPhilip Pfaffe     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
342282f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
342382f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
342482f2af35STobias Grosser   }
342582f2af35STobias Grosser 
3426f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3427f291c8d5SSiddharth Bhat   /// kernels.
3428f291c8d5SSiddharth Bhat   ///
3429f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3430f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
34318fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
34328fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3433f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3434f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
34358fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
343678027437SSiddharth Bhat                                           AllowCUDALibDevice))
3437f291c8d5SSiddharth Bhat         continue;
3438f291c8d5SSiddharth Bhat 
343978027437SSiddharth Bhat       for (Value *Op : Inst.operands())
3440dbe6d85bSNikita Popov         // Look for functions among operands of Inst.
3441dbe6d85bSNikita Popov         if (isa<Function>(Op->stripPointerCasts())) {
3442349506a9SNicola Zaghen           LLVM_DEBUG(dbgs()
3443349506a9SNicola Zaghen                      << Inst << " has illegal use of function in kernel.\n");
3444bccaea57SSiddharth Bhat           return true;
3445bccaea57SSiddharth Bhat         }
3446f291c8d5SSiddharth Bhat     }
3447bccaea57SSiddharth Bhat     return false;
3448bccaea57SSiddharth Bhat   }
3449bccaea57SSiddharth Bhat 
3450f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
34518fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3452bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3453bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
34548fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
34558fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3456bccaea57SSiddharth Bhat           return true;
3457bccaea57SSiddharth Bhat       } else {
3458bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3459bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3460bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
34618fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3462bccaea57SSiddharth Bhat             return true;
3463bccaea57SSiddharth Bhat       }
3464bccaea57SSiddharth Bhat     }
3465bccaea57SSiddharth Bhat     return false;
3466bccaea57SSiddharth Bhat   }
3467bccaea57SSiddharth Bhat 
346838fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
346938fc0aedSTobias Grosser   ///
347032837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
347132837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
347232837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
347338fc0aedSTobias Grosser     ScopAnnotator Annotator;
347438fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
347538fc0aedSTobias Grosser 
347638fc0aedSTobias Grosser     Region *R = &S->getRegion();
347738fc0aedSTobias Grosser 
347838fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
347938fc0aedSTobias Grosser 
348038fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
348138fc0aedSTobias Grosser 
348255cfb1fbSNikita Popov     PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(),
348355cfb1fbSNikita Popov                            IRInserter(Annotator));
348455cfb1fbSNikita Popov     Builder.SetInsertPoint(EnteringBB->getTerminator());
348538fc0aedSTobias Grosser 
348638fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
348738fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
348838fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
348938fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
349038fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
349138fc0aedSTobias Grosser     // code generating this scop.
349203346c27SSiddharth Bhat     BBPair StartExitBlocks;
349303346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
349403346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
34952d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3496256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
349738fc0aedSTobias Grosser 
349803346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
349903346c27SSiddharth Bhat 
35002d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
350117f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3502acf80064SEli Friedman 
350338fc0aedSTobias Grosser     // TODO: Handle LICM
350438fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
350538fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
3506cb1aef8dSTobias Grosser 
350700fd43b3SPhilip Pfaffe     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
35084170d6cdSpatacca     isl::ast_expr Condition =
35094170d6cdSpatacca         IslAst::buildRunCondition(*S, isl::manage_copy(Build));
351082f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
35114170d6cdSpatacca     Condition =
35124170d6cdSpatacca         isl::manage(isl_ast_expr_and(Condition.release(), SufficientCompute));
3513cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3514cb1aef8dSTobias Grosser 
35159e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
35169e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
351771dfb3ebSSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads()) {
35182fb847fbSTobias Grosser       // Patch the introduced branch condition to ensure that we always execute
35192fb847fbSTobias Grosser       // the original SCoP.
35202fb847fbSTobias Grosser       auto *FalseI1 = Builder.getFalse();
35212fb847fbSTobias Grosser       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
35222fb847fbSTobias Grosser       SplitBBTerm->setOperand(0, FalseI1);
35232fb847fbSTobias Grosser 
3524349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
35254ebeb356SSiddharth Bhat                                S->getFunction().getName() +
35264ebeb356SSiddharth Bhat                                " | Scop Region: " + S->getNameStr());
352771dfb3ebSSiddharth Bhat       // adjust the dominator tree accordingly.
352871dfb3ebSSiddharth Bhat       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
352971dfb3ebSSiddharth Bhat       assert(ExitingBlock);
353071dfb3ebSSiddharth Bhat       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
353171dfb3ebSSiddharth Bhat       assert(MergeBlock);
353271dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*StartBlock, Builder);
353371dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*ExitingBlock, Builder);
353471dfb3ebSSiddharth Bhat       auto *ExitingBB = S->getExitingBlock();
353571dfb3ebSSiddharth Bhat       assert(ExitingBB);
35369e3db2b7SSiddharth Bhat 
353771dfb3ebSSiddharth Bhat       DT->changeImmediateDominator(MergeBlock, ExitingBB);
353871dfb3ebSSiddharth Bhat       DT->eraseNode(ExitingBlock);
353971dfb3ebSSiddharth Bhat       isl_ast_node_free(Root);
354071dfb3ebSSiddharth Bhat     } else {
354171dfb3ebSSiddharth Bhat 
35427b9f5ca2SSiddharth Bhat       if (polly::PerfMonitoring) {
35437b9f5ca2SSiddharth Bhat         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
35447b9f5ca2SSiddharth Bhat         P.initialize();
35457b9f5ca2SSiddharth Bhat         P.insertRegionStart(SplitBlock->getTerminator());
35467b9f5ca2SSiddharth Bhat 
35477b9f5ca2SSiddharth Bhat         // TODO: actually think if this is the correct exiting block to place
35487b9f5ca2SSiddharth Bhat         // the `end` performance marker. Invariant load hoisting changes
35497b9f5ca2SSiddharth Bhat         // the CFG in a way that I do not precisely understand, so I
35507b9f5ca2SSiddharth Bhat         // (Siddharth<[email protected]>) should come back to this and
35517b9f5ca2SSiddharth Bhat         // think about which exiting block to use.
35527b9f5ca2SSiddharth Bhat         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
35537b9f5ca2SSiddharth Bhat         assert(ExitingBlock);
35547b9f5ca2SSiddharth Bhat         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
35557b9f5ca2SSiddharth Bhat         P.insertRegionEnd(MergeBlock->getTerminator());
35567b9f5ca2SSiddharth Bhat       }
35577b9f5ca2SSiddharth Bhat 
355871dfb3ebSSiddharth Bhat       NodeBuilder.addParameters(S->getContext().release());
35594170d6cdSpatacca       Value *RTC = NodeBuilder.createRTC(Condition.release());
3560cb1aef8dSTobias Grosser       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3561cb1aef8dSTobias Grosser 
356238fc0aedSTobias Grosser       Builder.SetInsertPoint(&*StartBlock->begin());
3563fa7b0802STobias Grosser 
356438fc0aedSTobias Grosser       NodeBuilder.create(Root);
356571dfb3ebSSiddharth Bhat     }
35665857b701STobias Grosser 
3567bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3568bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3569de244eb4STobias Grosser     /// point in running it on a GPU.
3570bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
357103346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3572bc653f20STobias Grosser 
35735857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
357403346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
357538fc0aedSTobias Grosser   }
357638fc0aedSTobias Grosser 
3577e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3578e938517eSTobias Grosser     S = &CurrentScop;
357938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
358038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
358138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
35827b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
358338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3584e938517eSTobias Grosser 
3585349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3586656e6295SSiddharth Bhat                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3587656e6295SSiddharth Bhat 
3588f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3589f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3590f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3591bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3592bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
35938fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
35948fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3595349506a9SNicola Zaghen       LLVM_DEBUG(
3596638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3597638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3598f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3599bccaea57SSiddharth Bhat       return false;
3600f291c8d5SSiddharth Bhat     }
3601bccaea57SSiddharth Bhat 
3602e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3603e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3604f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
360538fc0aedSTobias Grosser 
360602ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
360732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
360802ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3609638316daSSiddharth Bhat     } else {
3610349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3611638316daSSiddharth Bhat                         << " has empty PPCGGen->tree. Bailing out.\n");
361202ca346eSSingapuram Sanjay Srivallabh     }
361338fc0aedSTobias Grosser 
3614b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3615f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3616e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3617e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3618e938517eSTobias Grosser 
3619e938517eSTobias Grosser     return true;
3620e938517eSTobias Grosser   }
36219dfe4e7cSTobias Grosser 
36229dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
36239dfe4e7cSTobias Grosser 
36249dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
3625a4f447c2SMichael Kruse     ScopPass::getAnalysisUsage(AU);
3626a4f447c2SMichael Kruse 
36279dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
36289dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
36299dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
36305cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
36319dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
36329dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
36339dfe4e7cSTobias Grosser 
36349dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
36359dfe4e7cSTobias Grosser     //        region tree.
36369dfe4e7cSTobias Grosser   }
36379dfe4e7cSTobias Grosser };
363824222c73STobias Grosser } // namespace
36399dfe4e7cSTobias Grosser 
36409dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
36419dfe4e7cSTobias Grosser 
364217f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
364317f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
364417f01968SSiddharth Bhat   generator->Runtime = Runtime;
364517f01968SSiddharth Bhat   generator->Architecture = Arch;
364617f01968SSiddharth Bhat   return generator;
364717f01968SSiddharth Bhat }
36489dfe4e7cSTobias Grosser 
36499dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
36509dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
36519dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
36529dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
36539dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
36549dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
36559dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
36565cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
36579dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
36589dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3659