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"
25edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2674dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
2774dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
280133dc39SHeejin Ahn #include "llvm/IR/IntrinsicsNVPTX.h"
2974dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
30e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
318fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
322c831971SMichael Kruse #include "llvm/InitializePasses.h"
338fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
34031bb165SMichael Kruse #include "llvm/Support/SourceMgr.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39f384594dSTobias Grosser #include "isl/union_map.h"
40e8227804SMichael Kruse #include <algorithm>
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
46e938517eSTobias Grosser }
47e938517eSTobias Grosser 
489dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
499dfe4e7cSTobias Grosser 
509dfe4e7cSTobias Grosser using namespace polly;
519dfe4e7cSTobias Grosser using namespace llvm;
529dfe4e7cSTobias Grosser 
539dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
549dfe4e7cSTobias Grosser 
55f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
56f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
57681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
58f384594dSTobias Grosser                                   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,
6369b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, 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"),
6732837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6832837fe3STobias Grosser                                   cl::cat(PollyCategory));
6932837fe3STobias Grosser 
7074dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7174dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7274dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7374dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7474dc3cb4STobias Grosser 
7574dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7674dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7774dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7874dc3cb4STobias Grosser                               cl::cat(PollyCategory));
79b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
80b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
81b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
82b513b491STobias Grosser                                   cl::cat(PollyCategory));
83130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
84130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
85130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
86130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8774dc3cb4STobias Grosser 
88c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory;
89c4a4af47SSiddharth Bhat static cl::opt<bool, true>
90c4a4af47SSiddharth Bhat     XManagedMemory("polly-acc-codegen-managed-memory",
91abed4969SSiddharth Bhat                    cl::desc("Generate Host kernel code assuming"
92abed4969SSiddharth Bhat                             " that all memory has been"
93abed4969SSiddharth Bhat                             " declared as managed memory"),
94c4a4af47SSiddharth Bhat                    cl::location(PollyManagedMemory), cl::Hidden,
95c4a4af47SSiddharth Bhat                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
96abed4969SSiddharth Bhat 
9765d7f72fSSiddharth Bhat static cl::opt<bool>
9865d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
9965d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10065d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10165d7f72fSSiddharth Bhat                                        " kernel module."),
10265d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10365d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10465d7f72fSSiddharth Bhat 
1058fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1068fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1078fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1088fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1098fc6cdfbSTobias Grosser 
11074dc3cb4STobias Grosser static cl::opt<std::string>
11174dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11274dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11374dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
11474dc3cb4STobias Grosser 
11582f2af35STobias Grosser static cl::opt<int>
11682f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11782f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
11882f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
11982f2af35STobias Grosser 
1203dcb5351SMichael Kruse GPURuntime polly::GPURuntimeChoice;
1213dcb5351SMichael Kruse static cl::opt<GPURuntime, true> XGPURuntimeChoice(
1223dcb5351SMichael Kruse     "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"),
1233dcb5351SMichael Kruse     cl::values(clEnumValN(GPURuntime::CUDA, "libcudart",
1243dcb5351SMichael Kruse                           "use the CUDA Runtime API"),
1253dcb5351SMichael Kruse                clEnumValN(GPURuntime::OpenCL, "libopencl",
1263dcb5351SMichael Kruse                           "use the OpenCL Runtime API")),
1273dcb5351SMichael Kruse     cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA),
1283dcb5351SMichael Kruse     cl::ZeroOrMore, cl::cat(PollyCategory));
1293dcb5351SMichael Kruse 
1303dcb5351SMichael Kruse GPUArch polly::GPUArchChoice;
1313dcb5351SMichael Kruse static cl::opt<GPUArch, true>
1323dcb5351SMichael Kruse     XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"),
1333dcb5351SMichael Kruse                    cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64",
1343dcb5351SMichael Kruse                                          "target NVIDIA 64-bit architecture"),
1353dcb5351SMichael Kruse                               clEnumValN(GPUArch::SPIR32, "spir32",
1363dcb5351SMichael Kruse                                          "target SPIR 32-bit architecture"),
1373dcb5351SMichael Kruse                               clEnumValN(GPUArch::SPIR64, "spir64",
1383dcb5351SMichael Kruse                                          "target SPIR 64-bit architecture")),
1393dcb5351SMichael Kruse                    cl::location(polly::GPUArchChoice),
1403dcb5351SMichael Kruse                    cl::init(GPUArch::NVPTX64), cl::ZeroOrMore,
1413dcb5351SMichael Kruse                    cl::cat(PollyCategory));
1423dcb5351SMichael Kruse 
1437b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring;
1447b9f5ca2SSiddharth Bhat 
145638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
146638316daSSiddharth Bhat /// function name.
147638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
148638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
149638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
150638316daSSiddharth Bhat }
151638316daSSiddharth Bhat 
152a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
153a82f2d26SSiddharth Bhat /// used by live range reordering.
154a82f2d26SSiddharth Bhat ///
155a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
156a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
157a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
158a82f2d26SSiddharth Bhat struct MustKillsInfo {
159a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
160a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
161a82f2d26SSiddharth Bhat   ///
162a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
163a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
164a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
165a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
166a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
167a82f2d26SSiddharth Bhat   /// killed.
168a82f2d26SSiddharth Bhat   ///
169edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
170edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
171edfef5aeSSiddharth Bhat   ///     consequently all be killed.
172edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
173edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
174edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
175a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
176a82f2d26SSiddharth Bhat 
1779e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1789e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1799e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1809e3db2b7SSiddharth Bhat 
1819b41d095Spatacca   MustKillsInfo() : KillsSchedule() {}
182a82f2d26SSiddharth Bhat };
183a82f2d26SSiddharth Bhat 
184761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
185761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
186761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
187761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
188761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
189761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
190761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
191761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
192761e5b93SSiddharth Bhat 
193761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
194761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
195761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
196761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
197761e5b93SSiddharth Bhat     if (!R.contains(I))
198761e5b93SSiddharth Bhat       return false;
199761e5b93SSiddharth Bhat   }
200761e5b93SSiddharth Bhat   return true;
201761e5b93SSiddharth Bhat }
202761e5b93SSiddharth Bhat 
203a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
204a82f2d26SSiddharth Bhat ///
205a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
206a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
207a82f2d26SSiddharth Bhat /// PPCG.
208a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
209b65ccc43STobias Grosser   const isl::space ParamSpace = S.getParamSpace();
210a82f2d26SSiddharth Bhat   MustKillsInfo Info;
211a82f2d26SSiddharth Bhat 
212761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
213761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
214761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
215a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
216a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
217761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
218761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
21977eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
220a82f2d26SSiddharth Bhat   }
221a82f2d26SSiddharth Bhat 
222*bad3ebbaSRiccardo Mori   Info.TaggedMustKills = isl::union_map::empty(ParamSpace.ctx());
223*bad3ebbaSRiccardo Mori   Info.MustKills = isl::union_map::empty(ParamSpace.ctx());
224a82f2d26SSiddharth Bhat 
225a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
226a82f2d26SSiddharth Bhat   // schedule:
227a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
228a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
229a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
2309b41d095Spatacca   Info.KillsSchedule = {};
231a82f2d26SSiddharth Bhat 
232edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
233a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
234edfef5aeSSiddharth Bhat         S.getIslCtx(),
235edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
236a82f2d26SSiddharth Bhat 
237a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
238a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
239edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
240a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
241edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
242edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
243edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
244edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
245a82f2d26SSiddharth Bhat     //
246a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
247a82f2d26SSiddharth Bhat     // TaggedMustKill:
248edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
249a82f2d26SSiddharth Bhat 
250edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
251d70ea7feSTobias Grosser     isl::map StmtToScalar = isl::map::universe(ParamSpace);
252edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
253edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
254a82f2d26SSiddharth Bhat 
255a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
256edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
257edfef5aeSSiddharth Bhat         nullptr);
258a82f2d26SSiddharth Bhat 
259edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
260d70ea7feSTobias Grosser     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
261edfef5aeSSiddharth Bhat     PhantomRefToScalar =
262edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
263edfef5aeSSiddharth Bhat     PhantomRefToScalar =
264edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
265a82f2d26SSiddharth Bhat 
266edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
267edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
268a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
269a82f2d26SSiddharth Bhat 
2709e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2719e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2729e3db2b7SSiddharth Bhat 
273a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
274a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
275a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
276a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
277a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
278a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
279a82f2d26SSiddharth Bhat 
280a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
2817c7978a1Spatacca     if (!Info.KillsSchedule.is_null())
2825f865032STobias Grosser       Info.KillsSchedule = isl::manage(
2835f865032STobias Grosser           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
284a82f2d26SSiddharth Bhat     else
285a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
286a82f2d26SSiddharth Bhat   }
287a82f2d26SSiddharth Bhat 
288a82f2d26SSiddharth Bhat   return Info;
289a82f2d26SSiddharth Bhat }
290a82f2d26SSiddharth Bhat 
29160c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
29260c60025STobias Grosser ///
29360c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
29460c60025STobias Grosser /// of the scheduled ScopStmts.
29560c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
29635de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
29760c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
29860c60025STobias Grosser                                        isl_id *Id, void *User),
29960c60025STobias Grosser     void *UserIndex,
30060c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
301edb885cbSTobias Grosser     void *UserExpr) {
30260c60025STobias Grosser 
303edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
30460c60025STobias Grosser 
30535de9009SSiddharth Bhat   if (!Stmt || !Build_C)
306edb885cbSTobias Grosser     return NULL;
307edb885cbSTobias Grosser 
308718d04c6STobias Grosser   isl::ast_build Build = isl::manage_copy(Build_C);
3090813bd16SRiccardo Mori   isl::ctx Ctx = Build.ctx();
31035de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
311edb885cbSTobias Grosser 
312cff9696eSTobias Grosser   Stmt->setAstBuild(Build);
313cff9696eSTobias Grosser 
314edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
31535de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
316dcf8d696STobias Grosser     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
31735de9009SSiddharth Bhat 
31835de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
31935de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
32035de9009SSiddharth Bhat 
32135de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
32235de9009SSiddharth Bhat     MPA = MPA.coalesce();
32335de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
32435de9009SSiddharth Bhat 
32535de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
32635de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
32735de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
328edb885cbSTobias Grosser   }
329edb885cbSTobias Grosser 
33035de9009SSiddharth Bhat   return RefToExpr.release();
33160c60025STobias Grosser }
332f384594dSTobias Grosser 
333a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
334a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
335a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
336a90be207SSiddharth Bhat   if (bytes == 0)
337a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
338a90be207SSiddharth Bhat   return bytes;
339a90be207SSiddharth Bhat }
340a90be207SSiddharth Bhat 
34138fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
34238fc0aedSTobias Grosser ///
34338fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
344a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
34538fc0aedSTobias Grosser /// for generating GPU specific user nodes.
34638fc0aedSTobias Grosser ///
34738fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
34838fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
34938fc0aedSTobias Grosser public:
3502d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
35138fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
352acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
35317f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3542d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
35517f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
356edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
357edb885cbSTobias Grosser   }
35838fc0aedSTobias Grosser 
359fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
360fa7b0802STobias Grosser   void initializeAfterRTH();
361fa7b0802STobias Grosser 
362fa7b0802STobias Grosser   /// Finalize the generated scop.
36333ca0b0eSMichael Kruse   void finalize() override;
364fa7b0802STobias Grosser 
3655857b701STobias Grosser   /// Track if the full build process was successful.
3665857b701STobias Grosser   ///
3675857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3685857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3695857b701STobias Grosser   bool BuildSuccessful = true;
3705857b701STobias Grosser 
371bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
372bc653f20STobias Grosser   unsigned DeepestSequential = 0;
373bc653f20STobias Grosser 
374bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
375bc653f20STobias Grosser   unsigned DeepestParallel = 0;
376bc653f20STobias Grosser 
37779f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
37879f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
37979f13b9aSSingapuram Sanjay Srivallabh 
38038fc0aedSTobias Grosser private:
38174dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
38274dc3cb4STobias Grosser   ///
38374dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
38474dc3cb4STobias Grosser   /// more.
38574dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
38674dc3cb4STobias Grosser 
38713c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
38813c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3897287aeddSTobias Grosser 
390fa7b0802STobias Grosser   /// The current GPU context.
391fa7b0802STobias Grosser   Value *GPUContext;
392fa7b0802STobias Grosser 
393b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
394b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
395b513b491STobias Grosser 
39632837fe3STobias Grosser   /// A module containing GPU code.
39732837fe3STobias Grosser   ///
39832837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
39932837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
40032837fe3STobias Grosser 
40132837fe3STobias Grosser   /// The GPU program we generate code for.
40232837fe3STobias Grosser   gpu_prog *Prog;
40332837fe3STobias Grosser 
40417f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
40517f01968SSiddharth Bhat   GPURuntime Runtime;
40617f01968SSiddharth Bhat 
40717f01968SSiddharth Bhat   /// The GPU Architecture to target.
40817f01968SSiddharth Bhat   GPUArch Arch;
40917f01968SSiddharth Bhat 
410472f9654STobias Grosser   /// Class to free isl_ids.
411472f9654STobias Grosser   class IslIdDeleter {
412472f9654STobias Grosser   public:
413472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
414472f9654STobias Grosser   };
415472f9654STobias Grosser 
416472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
417472f9654STobias Grosser   ///
418472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
419472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
420472f9654STobias Grosser 
421edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
422edb885cbSTobias Grosser 
42338fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
42438fc0aedSTobias Grosser   ///
42538fc0aedSTobias Grosser   /// These AST nodes can be of type:
42638fc0aedSTobias Grosser   ///
42738fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
42838fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
42913c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4305260c041STobias Grosser   ///   - In-kernel synchronization
4315260c041STobias Grosser   ///   - In-kernel memory copy statement
43238fc0aedSTobias Grosser   ///
4331fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
43433ca0b0eSMichael Kruse   void createUser(__isl_take isl_ast_node *UserStmt) override;
43532837fe3STobias Grosser 
43633ca0b0eSMichael Kruse   void createFor(__isl_take isl_ast_node *Node) override;
43753c80387SPhilip Pfaffe 
43813c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
43913c78e4dSTobias Grosser 
44013c78e4dSTobias Grosser   /// Create code for a data transfer statement
44113c78e4dSTobias Grosser   ///
44213c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
44313c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
44413c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
44513c78e4dSTobias Grosser                           enum DataDirection Direction);
44613c78e4dSTobias Grosser 
447edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
448edb885cbSTobias Grosser   ///
449edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
450edb885cbSTobias Grosser   ///
451e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
452e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
453e53c924bSSiddharth Bhat   ///            kernel
454e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
455e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
456e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
457e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
458e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
459e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
460e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
461e53c924bSSiddharth Bhat   ///            Scops]
46243df2020STobias Grosser   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
46343df2020STobias Grosser              isl::space>
464f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
465edb885cbSTobias Grosser 
46679a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
46779a947c2STobias Grosser   ///
46879a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
46979a947c2STobias Grosser   ///
47079a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
47179a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
47279a947c2STobias Grosser 
473b99c1171STobias Grosser   /// Get the managed array pointer for sending host pointers to the device.
474abed4969SSiddharth Bhat   /// \note
475abed4969SSiddharth Bhat   /// This is to be used only with managed memory
476b99c1171STobias Grosser   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
477abed4969SSiddharth Bhat 
47879a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
47979a947c2STobias Grosser   ///
48079a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
48179a947c2STobias Grosser   ///
48279a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
48379a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
48479a947c2STobias Grosser 
485a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
486a90be207SSiddharth Bhat   /// parameters.
487a90be207SSiddharth Bhat   ///
488a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
489a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
490a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
491a90be207SSiddharth Bhat   ///                   parameter.
492a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
493a90be207SSiddharth Bhat                             int Index);
494a90be207SSiddharth Bhat 
49579a947c2STobias Grosser   /// Create kernel launch parameters.
49679a947c2STobias Grosser   ///
49779a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
49879a947c2STobias Grosser   /// @param F             The kernel function that has been created.
49957693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
50079a947c2STobias Grosser   ///
50179a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
50279a947c2STobias Grosser   ///          values that are passed to the kernel.
50357693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
50457693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
50579a947c2STobias Grosser 
506b513b491STobias Grosser   /// Create declarations for kernel variable.
507b513b491STobias Grosser   ///
508b513b491STobias Grosser   /// This includes shared memory declarations.
509b513b491STobias Grosser   ///
510b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
511b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
512b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
513b513b491STobias Grosser 
514c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
515c1c6a2a6STobias Grosser   ///
516c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
517c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
518c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
519c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
520c1c6a2a6STobias Grosser   /// as specified here.
521c1c6a2a6STobias Grosser   ///
522c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
523c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
524c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
525c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
526c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
527c1c6a2a6STobias Grosser                           Value *BlockDimZ);
528c1c6a2a6STobias Grosser 
52932837fe3STobias Grosser   /// Create GPU kernel.
53032837fe3STobias Grosser   ///
53132837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
53232837fe3STobias Grosser   ///
53332837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
53432837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
53532837fe3STobias Grosser 
53613c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
53713c78e4dSTobias Grosser   ///
53813c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
53913c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
54013c78e4dSTobias Grosser 
541aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
542aaabbbf8STobias Grosser   ///
543aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
544aaabbbf8STobias Grosser   ///
545aaabbbf8STobias Grosser   /// Example:
546aaabbbf8STobias Grosser   ///
547aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
548aaabbbf8STobias Grosser   ///     A[i + 42] += ...
549aaabbbf8STobias Grosser   ///
550aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
551aaabbbf8STobias Grosser   ///
552aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
553aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
554aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
555aaabbbf8STobias Grosser 
55600bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
55700bb5a99STobias Grosser   ///
55800bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
55900bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
56000bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
56100bb5a99STobias Grosser 
56232837fe3STobias Grosser   /// Create kernel function.
56332837fe3STobias Grosser   ///
56432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
56532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
56632837fe3STobias Grosser   /// start block of this newly created function.
56732837fe3STobias Grosser   ///
56832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
569edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
570f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
571f291c8d5SSiddharth Bhat   ///                         kernel.
572edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
573f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
574f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
57532837fe3STobias Grosser 
57632837fe3STobias Grosser   /// Create the declaration of a kernel function.
57732837fe3STobias Grosser   ///
57832837fe3STobias Grosser   /// The kernel function takes as arguments:
57932837fe3STobias Grosser   ///
58032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
581f6044bd0STobias Grosser   ///   - Host iterators
582c84a1995STobias Grosser   ///   - Parameters
58332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
58432837fe3STobias Grosser   ///
58532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
586edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
587edb885cbSTobias Grosser   ///
58832837fe3STobias Grosser   /// @returns The newly declared function.
589edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
590edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
59132837fe3STobias Grosser 
592472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
593472f9654STobias Grosser   ///
594472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
595472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
596472f9654STobias Grosser 
5972f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5982f3073b5SPhilipp Schaad   ///
599d71493cbSPhilip Pfaffe   /// @param Kernel The kernel to generate the function calls for.
600d71493cbSPhilip Pfaffe   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
601d71493cbSPhilip Pfaffe   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
6022f3073b5SPhilipp Schaad 
603f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
604f291c8d5SSiddharth Bhat   ///
605f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
606f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
607f291c8d5SSiddharth Bhat   ///
608f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
609f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
610f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
611f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
612f291c8d5SSiddharth Bhat   ///
613f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
614f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
615f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
616f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
617f291c8d5SSiddharth Bhat   ///
618f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
619f291c8d5SSiddharth Bhat   ///                         this kernel.
620f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
621f291c8d5SSiddharth Bhat 
622b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
623b513b491STobias Grosser   ///
624b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
625b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
626b513b491STobias Grosser 
627edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
628edb885cbSTobias Grosser   ///
629edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
630edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
631edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
632edb885cbSTobias Grosser 
6335260c041STobias Grosser   /// Create an in-kernel synchronization call.
6345260c041STobias Grosser   void createKernelSync();
6355260c041STobias Grosser 
63674dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
63774dc3cb4STobias Grosser   ///
63874dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
63974dc3cb4STobias Grosser   std::string createKernelASM();
64074dc3cb4STobias Grosser 
64174dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
64274dc3cb4STobias Grosser   ///
64374dc3cb4STobias Grosser   /// @param F The function to remove references to.
64474dc3cb4STobias Grosser   void clearDominators(Function *F);
64574dc3cb4STobias Grosser 
64674dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
64774dc3cb4STobias Grosser   ///
64874dc3cb4STobias Grosser   /// @param F The function to remove references to.
64974dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
65074dc3cb4STobias Grosser 
65174dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
65274dc3cb4STobias Grosser   ///
65374dc3cb4STobias Grosser   /// @param F The function to remove references to.
65474dc3cb4STobias Grosser   void clearLoops(Function *F);
65574dc3cb4STobias Grosser 
6568fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6578fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6588fc6cdfbSTobias Grosser 
6598fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6608fc6cdfbSTobias Grosser   void addCUDALibDevice();
6618fc6cdfbSTobias Grosser 
66232837fe3STobias Grosser   /// Finalize the generation of the kernel function.
66332837fe3STobias Grosser   ///
66432837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
66532837fe3STobias Grosser   /// dump its IR to stderr.
66657793596STobias Grosser   ///
66757793596STobias Grosser   /// @returns The Assembly string of the kernel.
66857793596STobias Grosser   std::string finalizeKernelFunction();
669fa7b0802STobias Grosser 
67051dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
67151dfc275STobias Grosser   ///
67251dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
673a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
67451dfc275STobias Grosser   /// the kernel terminates.
67551dfc275STobias Grosser   ///
67651dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
67751dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
67851dfc275STobias Grosser 
6797287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
680fa7b0802STobias Grosser   void allocateDeviceArrays();
681fa7b0802STobias Grosser 
682b99c1171STobias Grosser   /// Create code to prepare the managed device pointers.
683b99c1171STobias Grosser   void prepareManagedDeviceArrays();
684b99c1171STobias Grosser 
6857287aeddSTobias Grosser   /// Free all allocated device arrays.
6867287aeddSTobias Grosser   void freeDeviceArrays();
6877287aeddSTobias Grosser 
688fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
689fa7b0802STobias Grosser   ///
690fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
691fa7b0802STobias Grosser   Value *createCallInitContext();
692fa7b0802STobias Grosser 
69379a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
69479a947c2STobias Grosser   ///
69579a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
69679a947c2STobias Grosser   ///
69779a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
69879a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
69979a947c2STobias Grosser 
700fa7b0802STobias Grosser   /// Create a call to free the GPU context.
701fa7b0802STobias Grosser   ///
702fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
703fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
704fa7b0802STobias Grosser 
7057287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
7067287aeddSTobias Grosser   ///
7077287aeddSTobias Grosser   /// @param Size The size of memory to allocate
7087287aeddSTobias Grosser   ///
7097287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
710fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
7117287aeddSTobias Grosser 
7127287aeddSTobias Grosser   /// Create a call to free a device array.
7137287aeddSTobias Grosser   ///
7147287aeddSTobias Grosser   /// @param Array The device array to free.
7157287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
71613c78e4dSTobias Grosser 
71713c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
71813c78e4dSTobias Grosser   ///
71913c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
72013c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
72113c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
72213c78e4dSTobias Grosser                                       Value *Size);
72313c78e4dSTobias Grosser 
72413c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
72513c78e4dSTobias Grosser   ///
72613c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
72713c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
72813c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
72913c78e4dSTobias Grosser                                       Value *Size);
73057793596STobias Grosser 
731abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
732abed4969SSiddharth Bhat   /// \note
733abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
734abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
735abed4969SSiddharth Bhat 
73657793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
73757793596STobias Grosser   ///
73857793596STobias Grosser   /// @param Buffer The string describing the kernel.
73957793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
74057793596STobias Grosser   ///
74157793596STobias Grosser   /// @returns A pointer to a kernel object
74257793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
74357793596STobias Grosser 
74457793596STobias Grosser   /// Create a call to free a GPU kernel.
74557793596STobias Grosser   ///
74657793596STobias Grosser   /// @param GPUKernel THe kernel to free.
74757793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
74879a947c2STobias Grosser 
74979a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
75079a947c2STobias Grosser   ///
75179a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
75279a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
75379a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
75479a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
75579a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
75679a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
757a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
75879a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
75979a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
76079a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
76179a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
76279a947c2STobias Grosser                               Value *Parameters);
7631fb9b64dSTobias Grosser };
7641fb9b64dSTobias Grosser 
76579f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7661abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7671abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
76879f13b9aSSingapuram Sanjay Srivallabh }
76979f13b9aSSingapuram Sanjay Srivallabh 
770fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
771750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
772750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
773750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
774750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
775750160e2STobias Grosser 
776fa7b0802STobias Grosser   GPUContext = createCallInitContext();
777abed4969SSiddharth Bhat 
778c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
779fa7b0802STobias Grosser     allocateDeviceArrays();
780b99c1171STobias Grosser   else
781b99c1171STobias Grosser     prepareManagedDeviceArrays();
782fa7b0802STobias Grosser }
783fa7b0802STobias Grosser 
784fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
785c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
7867287aeddSTobias Grosser     freeDeviceArrays();
787abed4969SSiddharth Bhat 
788fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
789fa7b0802STobias Grosser   IslNodeBuilder::finalize();
790fa7b0802STobias Grosser }
791fa7b0802STobias Grosser 
792fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
793c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
794c4a4af47SSiddharth Bhat          "Managed memory will directly send host pointers "
795abed4969SSiddharth Bhat          "to the kernel. There is no need for device arrays");
7968ea1fc19STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
797fa7b0802STobias Grosser 
798fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
799fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
80013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
8017287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
8027287aeddSTobias Grosser     DevArrayName.append(Array->name);
803fa7b0802STobias Grosser 
80413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
805aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
806aaabbbf8STobias Grosser     if (Offset)
807aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
808aaabbbf8STobias Grosser           ArraySize,
809aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
810aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
81134eeabbcSSiddharth Bhat     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
81234eeabbcSSiddharth Bhat     // It makes no sense to have an array of size 0. The CUDA API will
81334eeabbcSSiddharth Bhat     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
81434eeabbcSSiddharth Bhat     // choose to be defensive and catch this at the compile phase. It is
81534eeabbcSSiddharth Bhat     // most likely that we are doing something wrong with size computation.
81634eeabbcSSiddharth Bhat     if (SizeSCEV->isZero()) {
81734eeabbcSSiddharth Bhat       errs() << getUniqueScopName(&S)
81834eeabbcSSiddharth Bhat              << " has computed array size 0: " << *ArraySize
81934eeabbcSSiddharth Bhat              << " | for array: " << *(ScopArray->getBasePtr())
82034eeabbcSSiddharth Bhat              << ". This is illegal, exiting.\n";
82134eeabbcSSiddharth Bhat       report_fatal_error("array size was computed to be 0");
82234eeabbcSSiddharth Bhat     }
82334eeabbcSSiddharth Bhat 
8247287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
8257287aeddSTobias Grosser     DevArray->setName(DevArrayName);
82613c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
827fa7b0802STobias Grosser   }
828fa7b0802STobias Grosser 
829fa7b0802STobias Grosser   isl_ast_build_free(Build);
830fa7b0802STobias Grosser }
831fa7b0802STobias Grosser 
832b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() {
833c4a4af47SSiddharth Bhat   assert(PollyManagedMemory &&
834b99c1171STobias Grosser          "Device array most only be prepared in managed-memory mode");
835b99c1171STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
836b99c1171STobias Grosser     gpu_array_info *Array = &Prog->array[i];
837b99c1171STobias Grosser     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
838b99c1171STobias Grosser     Value *HostPtr;
839b99c1171STobias Grosser 
840b99c1171STobias Grosser     if (gpu_array_is_scalar(Array))
841b99c1171STobias Grosser       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
842b99c1171STobias Grosser     else
843b99c1171STobias Grosser       HostPtr = ScopArray->getBasePtr();
844b99c1171STobias Grosser     HostPtr = getLatestValue(HostPtr);
845b99c1171STobias Grosser 
846b99c1171STobias Grosser     Value *Offset = getArrayOffset(Array);
847b99c1171STobias Grosser     if (Offset) {
848b99c1171STobias Grosser       HostPtr = Builder.CreatePointerCast(
849b99c1171STobias Grosser           HostPtr, ScopArray->getElementType()->getPointerTo());
8500ce9acf6SEli Friedman       HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
851b99c1171STobias Grosser     }
852b99c1171STobias Grosser 
853b99c1171STobias Grosser     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
854b99c1171STobias Grosser     DeviceAllocations[ScopArray] = HostPtr;
855b99c1171STobias Grosser   }
856b99c1171STobias Grosser }
857b99c1171STobias Grosser 
858c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
859c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
860c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
861c1c6a2a6STobias Grosser 
862c1c6a2a6STobias Grosser   for (auto &F : *M) {
863c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
864c1c6a2a6STobias Grosser       continue;
865c1c6a2a6STobias Grosser 
866c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
867c1c6a2a6STobias Grosser 
868c1c6a2a6STobias Grosser     Metadata *Elements[] = {
869c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
870c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
871c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
872c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
873c1c6a2a6STobias Grosser     };
874c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
875c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
876c1c6a2a6STobias Grosser   }
877c1c6a2a6STobias Grosser }
878c1c6a2a6STobias Grosser 
8797287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
880c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
88113c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
88213c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8837287aeddSTobias Grosser }
8847287aeddSTobias Grosser 
88557793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
88657793596STobias Grosser   const char *Name = "polly_getKernel";
88757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
88857793596STobias Grosser   Function *F = M->getFunction(Name);
88957793596STobias Grosser 
89057793596STobias Grosser   // If F is not available, declare it.
89157793596STobias Grosser   if (!F) {
89257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
89357793596STobias Grosser     std::vector<Type *> Args;
89457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89657793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
89757793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
89857793596STobias Grosser   }
89957793596STobias Grosser 
90057793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
90157793596STobias Grosser }
90257793596STobias Grosser 
90379a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
90479a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
90579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90679a947c2STobias Grosser   Function *F = M->getFunction(Name);
90779a947c2STobias Grosser 
90879a947c2STobias Grosser   // If F is not available, declare it.
90979a947c2STobias Grosser   if (!F) {
91079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
91179a947c2STobias Grosser     std::vector<Type *> Args;
91279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
91479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
91579a947c2STobias Grosser   }
91679a947c2STobias Grosser 
91779a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
91879a947c2STobias Grosser }
91979a947c2STobias Grosser 
92079a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
92179a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
92279a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
92379a947c2STobias Grosser                                             Value *Parameters) {
92479a947c2STobias Grosser   const char *Name = "polly_launchKernel";
92579a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92679a947c2STobias Grosser   Function *F = M->getFunction(Name);
92779a947c2STobias Grosser 
92879a947c2STobias Grosser   // If F is not available, declare it.
92979a947c2STobias Grosser   if (!F) {
93079a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93179a947c2STobias Grosser     std::vector<Type *> Args;
93279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
93879a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93979a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
94079a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
94179a947c2STobias Grosser   }
94279a947c2STobias Grosser 
943ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
94479a947c2STobias Grosser                          BlockDimZ, Parameters});
94579a947c2STobias Grosser }
94679a947c2STobias Grosser 
94757793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
94857793596STobias Grosser   const char *Name = "polly_freeKernel";
94957793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
95057793596STobias Grosser   Function *F = M->getFunction(Name);
95157793596STobias Grosser 
95257793596STobias Grosser   // If F is not available, declare it.
95357793596STobias Grosser   if (!F) {
95457793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
95557793596STobias Grosser     std::vector<Type *> Args;
95657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
95857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
95957793596STobias Grosser   }
96057793596STobias Grosser 
96157793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
96257793596STobias Grosser }
96357793596STobias Grosser 
9647287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
965c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
966c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
967abed4969SSiddharth Bhat          "for device");
9687287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
9697287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9707287aeddSTobias Grosser   Function *F = M->getFunction(Name);
9717287aeddSTobias Grosser 
9727287aeddSTobias Grosser   // If F is not available, declare it.
9737287aeddSTobias Grosser   if (!F) {
9747287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9757287aeddSTobias Grosser     std::vector<Type *> Args;
9767287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9777287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9787287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9797287aeddSTobias Grosser   }
9807287aeddSTobias Grosser 
9817287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9827287aeddSTobias Grosser }
9837287aeddSTobias Grosser 
984fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
985c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
986c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
987abed4969SSiddharth Bhat          "for device");
988fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
989fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
990fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
991fa7b0802STobias Grosser 
992fa7b0802STobias Grosser   // If F is not available, declare it.
993fa7b0802STobias Grosser   if (!F) {
994fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
995fa7b0802STobias Grosser     std::vector<Type *> Args;
996fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
997fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
998fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
999fa7b0802STobias Grosser   }
1000fa7b0802STobias Grosser 
1001fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
1002fa7b0802STobias Grosser }
1003fa7b0802STobias Grosser 
100413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
100513c78e4dSTobias Grosser                                                     Value *DeviceData,
100613c78e4dSTobias Grosser                                                     Value *Size) {
1007c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1008c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1009abed4969SSiddharth Bhat          "device and host");
101013c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
101113c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
101213c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
101313c78e4dSTobias Grosser 
101413c78e4dSTobias Grosser   // If F is not available, declare it.
101513c78e4dSTobias Grosser   if (!F) {
101613c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
101713c78e4dSTobias Grosser     std::vector<Type *> Args;
101813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
101913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
102013c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
102113c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
102213c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
102313c78e4dSTobias Grosser   }
102413c78e4dSTobias Grosser 
102513c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
102613c78e4dSTobias Grosser }
102713c78e4dSTobias Grosser 
102813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
102913c78e4dSTobias Grosser                                                     Value *HostData,
103013c78e4dSTobias Grosser                                                     Value *Size) {
1031c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1032c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1033abed4969SSiddharth Bhat          "device and host");
103413c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
103513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
103613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
103713c78e4dSTobias Grosser 
103813c78e4dSTobias Grosser   // If F is not available, declare it.
103913c78e4dSTobias Grosser   if (!F) {
104013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
104113c78e4dSTobias Grosser     std::vector<Type *> Args;
104213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
104313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
104413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
104513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
104613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
104713c78e4dSTobias Grosser   }
104813c78e4dSTobias Grosser 
104913c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
105013c78e4dSTobias Grosser }
105113c78e4dSTobias Grosser 
1052abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
1053c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1054abed4969SSiddharth Bhat                                "managed memory");
1055abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
1056abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1057abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
1058abed4969SSiddharth Bhat 
1059abed4969SSiddharth Bhat   // If F is not available, declare it.
1060abed4969SSiddharth Bhat   if (!F) {
1061abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1062abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1063abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
1064abed4969SSiddharth Bhat   }
1065abed4969SSiddharth Bhat 
1066abed4969SSiddharth Bhat   Builder.CreateCall(F);
1067abed4969SSiddharth Bhat }
1068abed4969SSiddharth Bhat 
1069fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
107017f01968SSiddharth Bhat   const char *Name;
107117f01968SSiddharth Bhat 
107217f01968SSiddharth Bhat   switch (Runtime) {
107317f01968SSiddharth Bhat   case GPURuntime::CUDA:
107417f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
107517f01968SSiddharth Bhat     break;
107617f01968SSiddharth Bhat   case GPURuntime::OpenCL:
107717f01968SSiddharth Bhat     Name = "polly_initContextCL";
107817f01968SSiddharth Bhat     break;
107917f01968SSiddharth Bhat   }
108017f01968SSiddharth Bhat 
1081fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1082fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1083fa7b0802STobias Grosser 
1084fa7b0802STobias Grosser   // If F is not available, declare it.
1085fa7b0802STobias Grosser   if (!F) {
1086fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1087fa7b0802STobias Grosser     std::vector<Type *> Args;
1088fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1089fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1090fa7b0802STobias Grosser   }
1091fa7b0802STobias Grosser 
1092fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1093fa7b0802STobias Grosser }
1094fa7b0802STobias Grosser 
1095fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1096fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1097fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1098fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1099fa7b0802STobias Grosser 
1100fa7b0802STobias Grosser   // If F is not available, declare it.
1101fa7b0802STobias Grosser   if (!F) {
1102fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1103fa7b0802STobias Grosser     std::vector<Type *> Args;
1104fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1105fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1106fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1107fa7b0802STobias Grosser   }
1108fa7b0802STobias Grosser 
1109fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1110fa7b0802STobias Grosser }
1111fa7b0802STobias Grosser 
11125260c041STobias Grosser /// Check if one string is a prefix of another.
11135260c041STobias Grosser ///
11145260c041STobias Grosser /// @param String The string in which to look for the prefix.
11155260c041STobias Grosser /// @param Prefix The prefix to look for.
11165260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
11175260c041STobias Grosser   return String.find(Prefix) == 0;
11185260c041STobias Grosser }
11195260c041STobias Grosser 
112013c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1121b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
112213c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
112313c78e4dSTobias Grosser 
112413c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1125718d04c6STobias Grosser     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1126f7face4bSSiddharth Bhat 
1127f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1128f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
112913c78e4dSTobias Grosser 
113013c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1131f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1132f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1133f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
113413c78e4dSTobias Grosser     }
113513c78e4dSTobias Grosser 
1136f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1137b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1138b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
113913c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
114013c78e4dSTobias Grosser   }
114113c78e4dSTobias Grosser   return ArraySize;
114213c78e4dSTobias Grosser }
114313c78e4dSTobias Grosser 
1144aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1145aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1146aaabbbf8STobias Grosser     return nullptr;
1147aaabbbf8STobias Grosser 
1148b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1149aaabbbf8STobias Grosser 
1150718d04c6STobias Grosser   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1151aaabbbf8STobias Grosser 
1152ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1153aaabbbf8STobias Grosser 
1154f482497cSpatacca   for (long i = 0, n = Min.tuple_dim(); i < n; i++)
1155ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1156aaabbbf8STobias Grosser 
1157ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1158aaabbbf8STobias Grosser     return nullptr;
1159aaabbbf8STobias Grosser   }
1160aaabbbf8STobias Grosser 
11610813bd16SRiccardo Mori   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.ctx(), 0));
1162aaabbbf8STobias Grosser 
1163f482497cSpatacca   for (long i = 0, n = Min.tuple_dim(); i < n; i++) {
1164aaabbbf8STobias Grosser     if (i > 0) {
1165ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1166ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1167ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1168ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1169aaabbbf8STobias Grosser     }
1170ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1171ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1172ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1173aaabbbf8STobias Grosser   }
1174aaabbbf8STobias Grosser 
1175ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1176aaabbbf8STobias Grosser }
1177aaabbbf8STobias Grosser 
1178b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1179abed4969SSiddharth Bhat                                              ScopArrayInfo *ArrayInfo) {
1180c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "Only used when you wish to get a host "
1181abed4969SSiddharth Bhat                                "pointer for sending data to the kernel, "
1182abed4969SSiddharth Bhat                                "with managed memory");
1183abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1184b99c1171STobias Grosser   it = DeviceAllocations.find(ArrayInfo);
1185b99c1171STobias Grosser   assert(it != DeviceAllocations.end() &&
1186b99c1171STobias Grosser          "Device array expected to be available");
1187abed4969SSiddharth Bhat   return it->second;
1188abed4969SSiddharth Bhat }
1189abed4969SSiddharth Bhat 
119013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
119113c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1192c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
119313c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
119413c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
119513c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
119613c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
119713c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
119813c78e4dSTobias Grosser 
119913c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1200aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
120113c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
120213c78e4dSTobias Grosser 
1203b06ff457STobias Grosser   Value *HostPtr;
1204b06ff457STobias Grosser 
1205b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1206b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1207b06ff457STobias Grosser   else
1208b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1209edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
121013c78e4dSTobias Grosser 
1211aaabbbf8STobias Grosser   if (Offset) {
1212aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1213aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
12140ce9acf6SEli Friedman     HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset);
1215aaabbbf8STobias Grosser   }
1216aaabbbf8STobias Grosser 
121713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
121813c78e4dSTobias Grosser 
1219aaabbbf8STobias Grosser   if (Offset) {
1220aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1221ff40087aSTobias Grosser         Size, Builder.CreateMul(
1222ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1223aaabbbf8STobias Grosser   }
1224aaabbbf8STobias Grosser 
122513c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
122613c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
122713c78e4dSTobias Grosser   else
122813c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
122913c78e4dSTobias Grosser 
123013c78e4dSTobias Grosser   isl_id_free(Id);
123113c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
123213c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
123313c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
123413c78e4dSTobias Grosser }
123513c78e4dSTobias Grosser 
12361fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
123732837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
123832837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
123932837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
124032837fe3STobias Grosser   isl_id_free(Id);
124132837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
124232837fe3STobias Grosser 
124332837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
124432837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
124532837fe3STobias Grosser     createKernel(UserStmt);
124662acb344STobias Grosser     if (PollyManagedMemory)
124762acb344STobias Grosser       createCallSynchronizeDevice();
124832837fe3STobias Grosser     isl_ast_expr_free(Expr);
124932837fe3STobias Grosser     return;
125032837fe3STobias Grosser   }
12519e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
12529e3db2b7SSiddharth Bhat     initializeAfterRTH();
12539e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12549e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12559e3db2b7SSiddharth Bhat     return;
12569e3db2b7SSiddharth Bhat   }
12579e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12589e3db2b7SSiddharth Bhat     finalize();
12599e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12609e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12619e3db2b7SSiddharth Bhat     return;
12629e3db2b7SSiddharth Bhat   }
126313c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1264c4a4af47SSiddharth Bhat     if (!PollyManagedMemory)
126513c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1266abed4969SSiddharth Bhat     else
1267abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1268abed4969SSiddharth Bhat 
126932837fe3STobias Grosser     isl_ast_expr_free(Expr);
127013c78e4dSTobias Grosser     return;
127113c78e4dSTobias Grosser   }
127213c78e4dSTobias Grosser 
127313c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1274c4a4af47SSiddharth Bhat     if (!PollyManagedMemory) {
127513c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1276abed4969SSiddharth Bhat     } else {
1277abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1278abed4969SSiddharth Bhat     }
127913c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
128038fc0aedSTobias Grosser     return;
128138fc0aedSTobias Grosser   }
128238fc0aedSTobias Grosser 
12835260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12845260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12855260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12865260c041STobias Grosser   isl_id_free(Anno);
12875260c041STobias Grosser 
12885260c041STobias Grosser   switch (KernelStmt->type) {
12895260c041STobias Grosser   case ppcg_kernel_domain:
1290edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12915260c041STobias Grosser     isl_ast_node_free(UserStmt);
12925260c041STobias Grosser     return;
12935260c041STobias Grosser   case ppcg_kernel_copy:
1294b513b491STobias Grosser     createKernelCopy(KernelStmt);
12955260c041STobias Grosser     isl_ast_expr_free(Expr);
12965260c041STobias Grosser     isl_ast_node_free(UserStmt);
12975260c041STobias Grosser     return;
12985260c041STobias Grosser   case ppcg_kernel_sync:
12995260c041STobias Grosser     createKernelSync();
13005260c041STobias Grosser     isl_ast_expr_free(Expr);
13015260c041STobias Grosser     isl_ast_node_free(UserStmt);
13025260c041STobias Grosser     return;
13035260c041STobias Grosser   }
13045260c041STobias Grosser 
13055260c041STobias Grosser   isl_ast_expr_free(Expr);
13065260c041STobias Grosser   isl_ast_node_free(UserStmt);
13075260c041STobias Grosser }
130853c80387SPhilip Pfaffe 
130953c80387SPhilip Pfaffe void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
131042ad8182SMichael Kruse   createForSequential(isl::manage(Node), false);
131153c80387SPhilip Pfaffe }
131253c80387SPhilip Pfaffe 
1313b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1314b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1315b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1316b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1317b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1318b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1319b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
13209c486eb3SMichael Kruse   Type *IndexTy = cast<PointerType>(GlobalAddr->getType())->getElementType();
1321b513b491STobias Grosser 
1322b513b491STobias Grosser   if (KernelStmt->u.c.read) {
13239c486eb3SMichael Kruse     LoadInst *Load = Builder.CreateLoad(IndexTy, GlobalAddr, "shared.read");
1324b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1325b513b491STobias Grosser   } else {
13269c486eb3SMichael Kruse     LoadInst *Load = Builder.CreateLoad(IndexTy, LocalAddr, "shared.write");
1327b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1328b513b491STobias Grosser   }
1329b513b491STobias Grosser }
13305260c041STobias Grosser 
1331edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1332edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1333edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1334edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1335edb885cbSTobias Grosser 
1336edb885cbSTobias Grosser   LoopToScevMapT LTS;
1337edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1338edb885cbSTobias Grosser 
1339edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1340edb885cbSTobias Grosser 
1341edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1342edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1343edb885cbSTobias Grosser   else
1344a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1345edb885cbSTobias Grosser }
1346edb885cbSTobias Grosser 
13475260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
13485260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13492f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
135017f01968SSiddharth Bhat 
135117f01968SSiddharth Bhat   Function *Sync;
135217f01968SSiddharth Bhat 
135317f01968SSiddharth Bhat   switch (Arch) {
13542f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
13552f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
13562f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
13572f3073b5SPhilipp Schaad 
13582f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
13592f3073b5SPhilipp Schaad     if (!Sync) {
13602f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13612f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13622f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13632f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13642f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13652f3073b5SPhilipp Schaad     }
13662f3073b5SPhilipp Schaad     break;
136717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
136817f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
136917f01968SSiddharth Bhat     break;
137017f01968SSiddharth Bhat   }
137117f01968SSiddharth Bhat 
13725260c041STobias Grosser   Builder.CreateCall(Sync, {});
13735260c041STobias Grosser }
13745260c041STobias Grosser 
1375edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1376edb885cbSTobias Grosser ///
1377edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1378edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1379edb885cbSTobias Grosser ///
1380edb885cbSTobias Grosser /// @param Node The node to collect references for.
1381edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1382edb885cbSTobias Grosser ///
1383edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1384edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1385edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1386edb885cbSTobias Grosser     return isl_bool_true;
1387edb885cbSTobias Grosser 
1388edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1389edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1390edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1391edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1392edb885cbSTobias Grosser   isl_id_free(Id);
1393edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1394edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1395edb885cbSTobias Grosser 
1396edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1397edb885cbSTobias Grosser     return isl_bool_true;
1398edb885cbSTobias Grosser 
1399edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1400edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1401edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1402edb885cbSTobias Grosser   isl_id_free(Id);
1403edb885cbSTobias Grosser 
140400bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1405edb885cbSTobias Grosser 
1406edb885cbSTobias Grosser   return isl_bool_true;
1407edb885cbSTobias Grosser }
1408edb885cbSTobias Grosser 
14098fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
14108fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
141156572c6aSSiddharth Bhat     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
141256572c6aSSiddharth Bhat     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
141356572c6aSSiddharth Bhat 
141456572c6aSSiddharth Bhat // A map from intrinsics to their corresponding libdevice functions.
141556572c6aSSiddharth Bhat const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
141656572c6aSSiddharth Bhat     {"llvm.exp.f64", "exp"},
141756572c6aSSiddharth Bhat     {"llvm.exp.f32", "expf"},
14186aac2773SBjorn Pettersson     {"llvm.powi.f64.i32", "powi"},
14196aac2773SBjorn Pettersson     {"llvm.powi.f32.i32", "powif"}};
14208fc6cdfbSTobias Grosser 
142166a05ad6SPhilip Pfaffe /// Return the corresponding CUDA libdevice function name @p Name.
142256572c6aSSiddharth Bhat /// Note that this function will try to convert instrinsics in the list
142356572c6aSSiddharth Bhat /// IntrinsicToLibdeviceFunc into libdevice functions.
142456572c6aSSiddharth Bhat /// This is because some intrinsics such as `exp`
142556572c6aSSiddharth Bhat /// are not supported by the NVPTX backend.
142656572c6aSSiddharth Bhat /// If this restriction of the backend is lifted, we should refactor our code
142756572c6aSSiddharth Bhat /// so that we use intrinsics whenever possible.
14288fc6cdfbSTobias Grosser ///
14298fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
14301a53b732SMichael Kruse std::string getCUDALibDeviceFuntion(StringRef NameRef) {
14311a53b732SMichael Kruse   std::string Name = NameRef.str();
143266a05ad6SPhilip Pfaffe   auto It = IntrinsicToLibdeviceFunc.find(Name);
143356572c6aSSiddharth Bhat   if (It != IntrinsicToLibdeviceFunc.end())
143466a05ad6SPhilip Pfaffe     return getCUDALibDeviceFuntion(It->second);
143556572c6aSSiddharth Bhat 
143666a05ad6SPhilip Pfaffe   if (CUDALibDeviceFunctions.count(Name))
14371a53b732SMichael Kruse     return ("__nv_" + Name);
14388fc6cdfbSTobias Grosser 
14398fc6cdfbSTobias Grosser   return "";
14408fc6cdfbSTobias Grosser }
14418fc6cdfbSTobias Grosser 
1442f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
14438fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1444f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1445f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
144654491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
144754491db6STobias Grosser   // "llvm.copysign".
144854491db6STobias Grosser   const StringRef Name = F->getName();
14498fc6cdfbSTobias Grosser 
145066a05ad6SPhilip Pfaffe   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
14518fc6cdfbSTobias Grosser     return true;
14528fc6cdfbSTobias Grosser 
145354491db6STobias Grosser   return F->isIntrinsic() &&
145454491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
145556572c6aSSiddharth Bhat           Name.startswith("llvm.copysign"));
1456f291c8d5SSiddharth Bhat }
1457f291c8d5SSiddharth Bhat 
1458f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1459f291c8d5SSiddharth Bhat ///
1460f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1461f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1462f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1463f291c8d5SSiddharth Bhat /// `Function`s.
1464f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1465f291c8d5SSiddharth Bhat 
1466f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1467f291c8d5SSiddharth Bhat static SetVector<Function *>
14688fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
14698fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1470f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1471f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1472f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1473f291c8d5SSiddharth Bhat     if (F) {
14748fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
14758fc6cdfbSTobias Grosser              "Code should have bailed out by "
1476f291c8d5SSiddharth Bhat              "this point if an invalid function "
1477f291c8d5SSiddharth Bhat              "were present in a kernel.");
1478f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1479f291c8d5SSiddharth Bhat     }
1480f291c8d5SSiddharth Bhat   }
1481f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1482f291c8d5SSiddharth Bhat }
1483f291c8d5SSiddharth Bhat 
148443df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
148543df2020STobias Grosser            isl::space>
1486f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1487edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1488edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1489edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
149043df2020STobias Grosser   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1491edb885cbSTobias Grosser   SubtreeReferences References = {
149243df2020STobias Grosser       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
149343df2020STobias Grosser       &ParamSpace};
1494edb885cbSTobias Grosser 
1495edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1496edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1497edb885cbSTobias Grosser 
1498e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1499e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1500e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1501e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1502e53c924bSSiddharth Bhat 
1503edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1504edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1505edb885cbSTobias Grosser 
1506e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1507edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1508e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1509e53c924bSSiddharth Bhat   }
1510e53c924bSSiddharth Bhat 
1511e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1512e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1513e53c924bSSiddharth Bhat   });
1514edb885cbSTobias Grosser 
1515edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1516d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1517edb885cbSTobias Grosser 
1518b65ccc43STobias Grosser   isl_space *Space = S.getParamSpace().release();
15193044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1520edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1521edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1522edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1523edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1524edb885cbSTobias Grosser     isl_id_free(Id);
1525edb885cbSTobias Grosser   }
1526edb885cbSTobias Grosser   isl_space_free(Space);
1527edb885cbSTobias Grosser 
15283044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1529edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1530edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1531edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1532edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1533edb885cbSTobias Grosser     isl_id_free(Id);
1534edb885cbSTobias Grosser   }
1535edb885cbSTobias Grosser 
1536f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1537f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1538f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1539f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1540f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1541f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1542f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1543f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1544f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
15458fc6cdfbSTobias Grosser 
15468fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
15478fc6cdfbSTobias Grosser 
1548f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
15498fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1550f291c8d5SSiddharth Bhat 
1551a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1552a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1553a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1554a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1555a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1556a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1557a1b2086aSSiddharth Bhat     else
1558a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1559a1b2086aSSiddharth Bhat   }
156043df2020STobias Grosser   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
156143df2020STobias Grosser                          ParamSpace);
1562edb885cbSTobias Grosser }
1563edb885cbSTobias Grosser 
156474dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
156574dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
156674dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
156774dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
156874dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
156974dc3cb4STobias Grosser 
157074dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
157174dc3cb4STobias Grosser     DT.eraseNode(BB);
157274dc3cb4STobias Grosser }
157374dc3cb4STobias Grosser 
157474dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
15754d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15764d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
157774dc3cb4STobias Grosser     if (L)
157874dc3cb4STobias Grosser       SE.forgetLoop(L);
157974dc3cb4STobias Grosser   }
15804d50ab86SPhilip Pfaffe }
158174dc3cb4STobias Grosser 
158274dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
1583c06a6380SPhilip Pfaffe   SmallSet<Loop *, 1> WorkList;
15844d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15854d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
15864d50ab86SPhilip Pfaffe     if (L)
1587c06a6380SPhilip Pfaffe       WorkList.insert(L);
15884d50ab86SPhilip Pfaffe   }
1589c06a6380SPhilip Pfaffe   for (auto *L : WorkList)
1590c06a6380SPhilip Pfaffe     LI.erase(L);
159174dc3cb4STobias Grosser }
159274dc3cb4STobias Grosser 
159379a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
159479a947c2STobias Grosser   std::vector<Value *> Sizes;
15958ea1fc19STobias Grosser   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
159679a947c2STobias Grosser 
1597718d04c6STobias Grosser   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
159879a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
15994d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
16004d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
16014d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
160279a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
160379a947c2STobias Grosser     Sizes.push_back(Res);
160479a947c2STobias Grosser   }
160579a947c2STobias Grosser 
160679a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
160779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
160879a947c2STobias Grosser 
160979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
161079a947c2STobias Grosser }
161179a947c2STobias Grosser 
161279a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
161379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
161479a947c2STobias Grosser   std::vector<Value *> Sizes;
161579a947c2STobias Grosser 
161679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
161779a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
161879a947c2STobias Grosser     Sizes.push_back(Res);
161979a947c2STobias Grosser   }
162079a947c2STobias Grosser 
162179a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
162279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
162379a947c2STobias Grosser 
162479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
162579a947c2STobias Grosser }
162679a947c2STobias Grosser 
1627a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1628a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1629a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
16300ce9acf6SEli Friedman       Parameters->getType()->getPointerElementType(), Parameters,
16310ce9acf6SEli Friedman       {Builder.getInt64(0), Builder.getInt64(Index)});
1632a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1633a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1634a90be207SSiddharth Bhat }
1635a90be207SSiddharth Bhat 
163657693272STobias Grosser Value *
163757693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
163857693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1639a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1640a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1641a90be207SSiddharth Bhat 
164250139f0fSPhilipp Schaad   // If we are using the OpenCL Runtime, we need to add the kernel argument
164350139f0fSPhilipp Schaad   // sizes to the end of the launch-parameter list, so OpenCL can determine
164450139f0fSPhilipp Schaad   // how big the respective kernel arguments are.
164550139f0fSPhilipp Schaad   // Here we need to reserve adequate space for that.
164650139f0fSPhilipp Schaad   Type *ArrayTy;
164750139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL)
164850139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
164950139f0fSPhilipp Schaad   else
165050139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
165179a947c2STobias Grosser 
165279a947c2STobias Grosser   BasicBlock *EntryBlock =
165379a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
165467726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
165579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
165667726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
165767726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
165879a947c2STobias Grosser 
165979a947c2STobias Grosser   int Index = 0;
166079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
166179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
166279a947c2STobias Grosser       continue;
166379a947c2STobias Grosser 
166479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1665206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
166679a947c2STobias Grosser 
166750139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1668a90be207SSiddharth Bhat       ArgSizes[Index] = SAI->getElemSizeInBytes();
1669a90be207SSiddharth Bhat 
1670abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1671c4a4af47SSiddharth Bhat     if (PollyManagedMemory) {
1672b99c1171STobias Grosser       DevArray = getManagedDeviceArray(&Prog->array[i],
1673b99c1171STobias Grosser                                        const_cast<ScopArrayInfo *>(SAI));
1674abed4969SSiddharth Bhat     } else {
1675abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
167679a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1677abed4969SSiddharth Bhat     }
1678abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1679abed4969SSiddharth Bhat                                   "initialized");
1680aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1681aaabbbf8STobias Grosser 
1682aaabbbf8STobias Grosser     if (Offset) {
1683aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1684aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
16850ce9acf6SEli Friedman       DevArray = Builder.CreateGEP(SAI->getElementType(), DevArray,
16860ce9acf6SEli Friedman                                    Builder.CreateNeg(Offset));
1687aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1688aaabbbf8STobias Grosser     }
1689fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
16900ce9acf6SEli Friedman         ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1691aaabbbf8STobias Grosser 
1692fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1693abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1694c4a4af47SSiddharth Bhat       if (PollyManagedMemory)
1695abed4969SSiddharth Bhat         ValPtr = DevArray;
1696abed4969SSiddharth Bhat       else
1697abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1698abed4969SSiddharth Bhat 
1699abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1700abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1701fe74a7a1STobias Grosser       Value *ValPtrCast =
1702fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1703fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1704fe74a7a1STobias Grosser     } else {
170567726b32STobias Grosser       Instruction *Param =
170667726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
170767726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
170879a947c2STobias Grosser                          EntryBlock->getTerminator());
170979a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
171079a947c2STobias Grosser       Value *ParamTyped =
171179a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
171279a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1713fe74a7a1STobias Grosser     }
171479a947c2STobias Grosser     Index++;
171579a947c2STobias Grosser   }
171679a947c2STobias Grosser 
1717a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1718a490147cSTobias Grosser 
1719a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1720a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1721a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1722a490147cSTobias Grosser     isl_id_free(Id);
1723a90be207SSiddharth Bhat 
172450139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1725a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1726a90be207SSiddharth Bhat 
172767726b32STobias Grosser     Instruction *Param =
172867726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
172967726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1730a490147cSTobias Grosser                        EntryBlock->getTerminator());
1731a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1732a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1733a490147cSTobias Grosser     Index++;
1734a490147cSTobias Grosser   }
1735a490147cSTobias Grosser 
1736d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1737d8b94bcaSTobias Grosser 
1738d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1739d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1740d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1741a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1742a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1743d8b94bcaSTobias Grosser     isl_id_free(Id);
1744a90be207SSiddharth Bhat 
174550139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1746a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1747a90be207SSiddharth Bhat 
174867726b32STobias Grosser     Instruction *Param =
174967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
175067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1751d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1752d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1753a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1754d8b94bcaSTobias Grosser     Index++;
1755d8b94bcaSTobias Grosser   }
1756d8b94bcaSTobias Grosser 
175757693272STobias Grosser   for (auto Val : SubtreeValues) {
175850139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1759a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1760a90be207SSiddharth Bhat 
176167726b32STobias Grosser     Instruction *Param =
176267726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
176367726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
176457693272STobias Grosser                        EntryBlock->getTerminator());
176557693272STobias Grosser     Builder.CreateStore(Val, Param);
1766a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1767a90be207SSiddharth Bhat     Index++;
1768a90be207SSiddharth Bhat   }
1769a90be207SSiddharth Bhat 
177050139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL) {
1771a90be207SSiddharth Bhat     for (int i = 0; i < NumArgs; i++) {
1772a90be207SSiddharth Bhat       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1773a90be207SSiddharth Bhat       Instruction *Param =
1774a90be207SSiddharth Bhat           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1775a90be207SSiddharth Bhat                          Launch + "_param_size_" + std::to_string(i),
1776a90be207SSiddharth Bhat                          EntryBlock->getTerminator());
1777a90be207SSiddharth Bhat       Builder.CreateStore(Val, Param);
1778a90be207SSiddharth Bhat       insertStoreParameter(Parameters, Param, Index);
177957693272STobias Grosser       Index++;
178057693272STobias Grosser     }
178150139f0fSPhilipp Schaad   }
178257693272STobias Grosser 
178379a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
178479a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
178579a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
178679a947c2STobias Grosser }
178779a947c2STobias Grosser 
1788f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1789f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1790f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
17911a53b732SMichael Kruse     const std::string ClonedFnName = Fn->getName().str();
1792f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1793f291c8d5SSiddharth Bhat     if (!Clone)
1794f291c8d5SSiddharth Bhat       Clone =
1795f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1796f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1797f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1798f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1799f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1800f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1801f291c8d5SSiddharth Bhat   }
1802f291c8d5SSiddharth Bhat }
180332837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
180432837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
180532837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
180632837fe3STobias Grosser   isl_id_free(Id);
180732837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
180832837fe3STobias Grosser 
1809bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1810e8227804SMichael Kruse     DeepestParallel = std::max(
1811e8227804SMichael Kruse         DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1812bc653f20STobias Grosser   else
1813e8227804SMichael Kruse     DeepestSequential = std::max(
1814e8227804SMichael Kruse         DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1815bc653f20STobias Grosser 
1816c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1817c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1818c1c6a2a6STobias Grosser 
1819f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1820f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1821e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
182243df2020STobias Grosser   isl::space ParamSpace;
182343df2020STobias Grosser   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1824e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1825edb885cbSTobias Grosser 
182643df2020STobias Grosser   // Add parameters that appear only in the access function to the kernel
182743df2020STobias Grosser   // space. This is important to make sure that all isl_ids are passed as
182843df2020STobias Grosser   // parameters to the kernel, even though we may not have all parameters
182943df2020STobias Grosser   // in the context to improve compile time.
183043df2020STobias Grosser   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
183143df2020STobias Grosser 
183232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
183332837fe3STobias Grosser 
183432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1835472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1836edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1837587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1838b06ff457STobias Grosser   ScalarMap.clear();
1839c52b71dbSTobias Grosser   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1840c52b71dbSTobias Grosser   EscapeMap.clear();
184132837fe3STobias Grosser 
1842edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1843edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1844edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1845edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1846edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1847edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1848edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1849edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1850edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1851edb885cbSTobias Grosser     SubtreeValues.insert(V);
1852edb885cbSTobias Grosser   }
1853edb885cbSTobias Grosser 
1854f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1855f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
185632837fe3STobias Grosser 
185759ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
185859ab0705STobias Grosser 
185951dfc275STobias Grosser   finalizeKernelArguments(Kernel);
186074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
18612f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1862c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
186374dc3cb4STobias Grosser   clearDominators(F);
186474dc3cb4STobias Grosser   clearScalarEvolution(F);
186574dc3cb4STobias Grosser   clearLoops(F);
186674dc3cb4STobias Grosser 
1867472f9654STobias Grosser   IDToValue = HostIDs;
186832837fe3STobias Grosser 
1869b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1870b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1871c52b71dbSTobias Grosser   EscapeMap = std::move(HostEscapeMap);
1872edb885cbSTobias Grosser   IDToSAI.clear();
187374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
187474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
18754d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
187674dc3cb4STobias Grosser   LocalArrays.clear();
1877edb885cbSTobias Grosser 
187851dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
187951dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
188057693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
188179a947c2STobias Grosser 
188279f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
188357793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
188457793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
188557793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
188679a947c2STobias Grosser 
188779a947c2STobias Grosser   Value *GridDimX, *GridDimY;
188879a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
188979a947c2STobias Grosser 
189079a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
189179a947c2STobias Grosser                          BlockDimZ, Parameters);
189257793596STobias Grosser   createCallFreeKernel(GPUKernel);
1893b513b491STobias Grosser 
1894b513b491STobias Grosser   for (auto Id : KernelIds)
1895b513b491STobias Grosser     isl_id_free(Id);
1896b513b491STobias Grosser 
1897b513b491STobias Grosser   KernelIds.clear();
189832837fe3STobias Grosser }
189932837fe3STobias Grosser 
190032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
190132837fe3STobias Grosser ///
190232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
190332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1904d277fedaSSiddharth Bhat   std::string Ret = "";
190532837fe3STobias Grosser 
1906d277fedaSSiddharth Bhat   if (!is64Bit) {
1907d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190830caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1909d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1910d277fedaSSiddharth Bhat   } else {
1911d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
191230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1913d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1914d277fedaSSiddharth Bhat   }
191532837fe3STobias Grosser 
191632837fe3STobias Grosser   return Ret;
191732837fe3STobias Grosser }
191832837fe3STobias Grosser 
19192f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
19202f3073b5SPhilipp Schaad ///
19212f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
19222f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
19232f3073b5SPhilipp Schaad   std::string Ret = "";
19242f3073b5SPhilipp Schaad 
19252f3073b5SPhilipp Schaad   if (!is64Bit) {
19262f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-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   } else {
19312f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
193230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19332f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19342f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19352f3073b5SPhilipp Schaad   }
19362f3073b5SPhilipp Schaad 
19372f3073b5SPhilipp Schaad   return Ret;
19382f3073b5SPhilipp Schaad }
19392f3073b5SPhilipp Schaad 
1940edb885cbSTobias Grosser Function *
1941edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1942edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
194332837fe3STobias Grosser   std::vector<Type *> Args;
194479f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
194532837fe3STobias Grosser 
19462f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
19472f3073b5SPhilipp Schaad 
194832837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
194932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
195032837fe3STobias Grosser       continue;
195132837fe3STobias Grosser 
1952fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1953fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1954206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1955fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
19562f3073b5SPhilipp Schaad       MemoryType.push_back(
19572f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1958fe74a7a1STobias Grosser     } else {
1959d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1960d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
19612f3073b5SPhilipp Schaad       MemoryType.push_back(
19622f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
196332837fe3STobias Grosser     }
1964fe74a7a1STobias Grosser   }
196532837fe3STobias Grosser 
1966f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1967f6044bd0STobias Grosser 
19682f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1969f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
19702f3073b5SPhilipp Schaad     MemoryType.push_back(
19712f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19722f3073b5SPhilipp Schaad   }
1973f6044bd0STobias Grosser 
1974c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1975c84a1995STobias Grosser 
1976cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1977cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1978cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1979cf66ef26STobias Grosser     isl_id_free(Id);
1980cf66ef26STobias Grosser     Args.push_back(Val->getType());
19812f3073b5SPhilipp Schaad     MemoryType.push_back(
19822f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1983cf66ef26STobias Grosser   }
1984c84a1995STobias Grosser 
19852f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1986edb885cbSTobias Grosser     Args.push_back(V->getType());
19872f3073b5SPhilipp Schaad     MemoryType.push_back(
19882f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19892f3073b5SPhilipp Schaad   }
1990edb885cbSTobias Grosser 
199132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
199232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
199332837fe3STobias Grosser                               GPUModule.get());
199417f01968SSiddharth Bhat 
19952f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
19962f3073b5SPhilipp Schaad 
19972f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
19982f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
19992f3073b5SPhilipp Schaad   }
20002f3073b5SPhilipp Schaad 
20012f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
20022f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
20032f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
20042f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
20052f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20062f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
20072f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20082f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
20092f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20102f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
20112f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20122f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
20132f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
20142f3073b5SPhilipp Schaad   }
20152f3073b5SPhilipp Schaad 
201617f01968SSiddharth Bhat   switch (Arch) {
201717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
201832837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
201917f01968SSiddharth Bhat     break;
20202f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20212f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20222f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
20232f3073b5SPhilipp Schaad     break;
202417f01968SSiddharth Bhat   }
202532837fe3STobias Grosser 
202632837fe3STobias Grosser   auto Arg = FN->arg_begin();
202732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
202832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
202932837fe3STobias Grosser       continue;
203032837fe3STobias Grosser 
2031edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
2032edb885cbSTobias Grosser 
2033edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2034718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2035edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
2036edb885cbSTobias Grosser     Value *Val = &*Arg;
2037edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2038edb885cbSTobias Grosser     isl_ast_build *Build =
2039edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
2040f5aff704SRoman Gareev     Sizes.push_back(nullptr);
20413044dc51SMichael Kruse     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2042edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
20439e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2044edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
2045edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
2046edb885cbSTobias Grosser     }
2047edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
20484d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
204974dc3cb4STobias Grosser     LocalArrays.push_back(Val);
2050edb885cbSTobias Grosser 
2051edb885cbSTobias Grosser     isl_ast_build_free(Build);
2052b513b491STobias Grosser     KernelIds.push_back(Id);
2053edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
205432837fe3STobias Grosser     Arg++;
205532837fe3STobias Grosser   }
205632837fe3STobias Grosser 
2057f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
2058f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2059f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
2060f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
2061f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2062f6044bd0STobias Grosser     Arg++;
2063f6044bd0STobias Grosser   }
2064f6044bd0STobias Grosser 
2065c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
2066c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2067c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
206812453403STobias Grosser     Value *Val = IDToValue[Id];
206912453403STobias Grosser     ValueMap[Val] = &*Arg;
2070c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
2071c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2072c84a1995STobias Grosser     Arg++;
2073c84a1995STobias Grosser   }
2074c84a1995STobias Grosser 
2075edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
2076edb885cbSTobias Grosser     Arg->setName(V->getName());
2077edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
2078edb885cbSTobias Grosser     Arg++;
2079edb885cbSTobias Grosser   }
2080edb885cbSTobias Grosser 
208132837fe3STobias Grosser   return FN;
208232837fe3STobias Grosser }
208332837fe3STobias Grosser 
2084472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
208517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
208617f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
2087472f9654STobias Grosser 
208817f01968SSiddharth Bhat   switch (Arch) {
20892f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20902f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20912f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
209217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
209317f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
209417f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
209517f01968SSiddharth Bhat 
209617f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
209717f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
209817f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
209917f01968SSiddharth Bhat     break;
210017f01968SSiddharth Bhat   }
2101472f9654STobias Grosser 
2102472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2103472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
2104472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2105472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2106472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2107472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2108472f9654STobias Grosser     IDToValue[Id] = Val;
2109472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2110472f9654STobias Grosser   };
2111472f9654STobias Grosser 
2112472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2113472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2114472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2115472f9654STobias Grosser   }
2116472f9654STobias Grosser 
2117472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2118472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2119472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2120472f9654STobias Grosser   }
2121472f9654STobias Grosser }
2122472f9654STobias Grosser 
2123d71493cbSPhilip Pfaffe void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2124d71493cbSPhilip Pfaffe                                            bool SizeTypeIs64bit) {
21252f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
21262f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
21272f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
21282f3073b5SPhilipp Schaad 
21292f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
21302f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
21312f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
2132d71493cbSPhilip Pfaffe   IntegerType *SizeT =
2133d71493cbSPhilip Pfaffe       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
21342f3073b5SPhilipp Schaad 
2135d71493cbSPhilip Pfaffe   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2136d71493cbSPhilip Pfaffe                            IntegerType *SizeT) mutable {
21372f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21382f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
21392f3073b5SPhilipp Schaad 
21402f3073b5SPhilipp Schaad     // If FN is not available, declare it.
21412f3073b5SPhilipp Schaad     if (!FN) {
21422f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
21432f3073b5SPhilipp Schaad       std::vector<Type *> Args;
2144d71493cbSPhilip Pfaffe       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
21452f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
21462f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
21472f3073b5SPhilipp Schaad     }
21482f3073b5SPhilipp Schaad 
21492f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
2150d71493cbSPhilip Pfaffe     if (SizeT == Builder.getInt32Ty())
21512f3073b5SPhilipp Schaad       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
21522f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
21532f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
21542f3073b5SPhilipp Schaad   };
21552f3073b5SPhilipp Schaad 
21562f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
2157d71493cbSPhilip Pfaffe     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
21582f3073b5SPhilipp Schaad 
21592f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
2160d71493cbSPhilip Pfaffe     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
21612f3073b5SPhilipp Schaad }
21622f3073b5SPhilipp Schaad 
216300bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
216400bb5a99STobias Grosser   auto Arg = FN->arg_begin();
216500bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
216600bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
216700bb5a99STobias Grosser       continue;
216800bb5a99STobias Grosser 
216900bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2170718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
217100bb5a99STobias Grosser     isl_id_free(Id);
217200bb5a99STobias Grosser 
217300bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
217400bb5a99STobias Grosser       Arg++;
217500bb5a99STobias Grosser       continue;
217600bb5a99STobias Grosser     }
217700bb5a99STobias Grosser 
2178fe74a7a1STobias Grosser     Value *Val = &*Arg;
2179fe74a7a1STobias Grosser 
2180fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
218100bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2182fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
21839c486eb3SMichael Kruse       Val = Builder.CreateLoad(SAI->getElementType(), TypedArgPtr);
2184fe74a7a1STobias Grosser     }
2185fe74a7a1STobias Grosser 
2186fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
218700bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
218800bb5a99STobias Grosser 
218900bb5a99STobias Grosser     Arg++;
219000bb5a99STobias Grosser   }
219100bb5a99STobias Grosser }
219200bb5a99STobias Grosser 
219351dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
219451dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
219551dfc275STobias Grosser   auto Arg = FN->arg_begin();
219651dfc275STobias Grosser 
219751dfc275STobias Grosser   bool StoredScalar = false;
219851dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
219951dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
220051dfc275STobias Grosser       continue;
220151dfc275STobias Grosser 
220251dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2203718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
220451dfc275STobias Grosser     isl_id_free(Id);
220551dfc275STobias Grosser 
220651dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
220751dfc275STobias Grosser       Arg++;
220851dfc275STobias Grosser       continue;
220951dfc275STobias Grosser     }
221051dfc275STobias Grosser 
221151dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
221251dfc275STobias Grosser       Arg++;
221351dfc275STobias Grosser       continue;
221451dfc275STobias Grosser     }
221551dfc275STobias Grosser 
221651dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
221751dfc275STobias Grosser     Value *ArgPtr = &*Arg;
221851dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
221951dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
22209c486eb3SMichael Kruse     Value *Val = Builder.CreateLoad(SAI->getElementType(), Alloca);
222151dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
222251dfc275STobias Grosser     StoredScalar = true;
222351dfc275STobias Grosser 
222451dfc275STobias Grosser     Arg++;
222551dfc275STobias Grosser   }
222651dfc275STobias Grosser 
2227638316daSSiddharth Bhat   if (StoredScalar) {
222851dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
222951dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
223051dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
223151dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2232638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
223351dfc275STobias Grosser       BuildSuccessful = 0;
2234349506a9SNicola Zaghen       LLVM_DEBUG(
2235638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2236638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2237638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2238638316daSSiddharth Bhat     }
2239638316daSSiddharth Bhat   }
224051dfc275STobias Grosser }
224151dfc275STobias Grosser 
2242b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2243b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2244b513b491STobias Grosser 
2245b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2246b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2247b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2248206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2249b513b491STobias Grosser 
2250f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2251b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2252b513b491STobias Grosser 
2253f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2254928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2255b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2256f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2257b513b491STobias Grosser       isl_val_free(Val);
2258b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2259928d7573STobias Grosser     }
2260928d7573STobias Grosser 
2261928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2262928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2263928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2264928d7573STobias Grosser       isl_val_free(Val);
2265b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2266b513b491STobias Grosser     }
2267b513b491STobias Grosser 
2268130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2269130ca30fSTobias Grosser     Value *Allocation;
2270130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2271130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2272130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2273130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2274f7b3ae65SMichael Kruse       GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8));
2275f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2276f919d8b3STobias Grosser 
2277130ca30fSTobias Grosser       Allocation = GlobalVar;
2278130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2279130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2280130ca30fSTobias Grosser     } else {
2281130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2282130ca30fSTobias Grosser     }
22834d5a9172STobias Grosser     SAI =
22844d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
228500fd43b3SPhilip Pfaffe     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2286130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2287130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2288b513b491STobias Grosser     KernelIds.push_back(Id);
2289b513b491STobias Grosser     IDToSAI[Id] = SAI;
2290b513b491STobias Grosser   }
2291b513b491STobias Grosser }
2292b513b491STobias Grosser 
2293f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2294f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2295f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
229679f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
229732837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
229817f01968SSiddharth Bhat 
229917f01968SSiddharth Bhat   switch (Arch) {
230017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
230117f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
230232837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
230317f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
230417f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
230532837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
230617f01968SSiddharth Bhat     break;
23072f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23082f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
23092f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
23102f3073b5SPhilipp Schaad     break;
23112f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23122f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
23132f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
23142f3073b5SPhilipp Schaad     break;
231517f01968SSiddharth Bhat   }
231632837fe3STobias Grosser 
2317edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
231832837fe3STobias Grosser 
231959ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
232032837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
232132837fe3STobias Grosser 
232259ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
232359ab0705STobias Grosser 
232432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
232532837fe3STobias Grosser   Builder.CreateRetVoid();
232632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2327472f9654STobias Grosser 
2328629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2329629109b6STobias Grosser 
233000bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2331b513b491STobias Grosser   createKernelVariables(Kernel, FN);
23322f3073b5SPhilipp Schaad 
23332f3073b5SPhilipp Schaad   switch (Arch) {
23342f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2335472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
23362f3073b5SPhilipp Schaad     break;
23372f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
2338d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, false);
2339d71493cbSPhilip Pfaffe     break;
23402f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
2341d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, true);
23422f3073b5SPhilipp Schaad     break;
23432f3073b5SPhilipp Schaad   }
234432837fe3STobias Grosser }
234532837fe3STobias Grosser 
234674dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
234717f01968SSiddharth Bhat   llvm::Triple GPUTriple;
234817f01968SSiddharth Bhat 
234917f01968SSiddharth Bhat   switch (Arch) {
235017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
235117f01968SSiddharth Bhat     switch (Runtime) {
235217f01968SSiddharth Bhat     case GPURuntime::CUDA:
235317f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
235417f01968SSiddharth Bhat       break;
235517f01968SSiddharth Bhat     case GPURuntime::OpenCL:
235617f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
235717f01968SSiddharth Bhat       break;
235817f01968SSiddharth Bhat     }
235917f01968SSiddharth Bhat     break;
23602f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23612f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23622f3073b5SPhilipp Schaad     std::string SPIRAssembly;
23632f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
23642f3073b5SPhilipp Schaad     IROstream << *GPUModule;
23652f3073b5SPhilipp Schaad     IROstream.flush();
23662f3073b5SPhilipp Schaad     return SPIRAssembly;
236717f01968SSiddharth Bhat   }
236817f01968SSiddharth Bhat 
236974dc3cb4STobias Grosser   std::string ErrMsg;
237074dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
237174dc3cb4STobias Grosser 
237274dc3cb4STobias Grosser   if (!GPUTarget) {
237374dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
237474dc3cb4STobias Grosser     return "";
237574dc3cb4STobias Grosser   }
237674dc3cb4STobias Grosser 
237774dc3cb4STobias Grosser   TargetOptions Options;
237874dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
237917f01968SSiddharth Bhat 
238017f01968SSiddharth Bhat   std::string subtarget;
238117f01968SSiddharth Bhat 
238217f01968SSiddharth Bhat   switch (Arch) {
238317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
238417f01968SSiddharth Bhat     subtarget = CudaVersion;
238517f01968SSiddharth Bhat     break;
23862f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23872f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23882f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
238917f01968SSiddharth Bhat   }
239017f01968SSiddharth Bhat 
239117f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
239217f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
239374dc3cb4STobias Grosser 
239474dc3cb4STobias Grosser   SmallString<0> ASMString;
239574dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
239674dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
239774dc3cb4STobias Grosser 
239874dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
239974dc3cb4STobias Grosser 
24001dfede31SReid Kleckner   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile,
24019a45114bSPeter Collingbourne                                    true /* verify */)) {
240274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
240374dc3cb4STobias Grosser     return "";
240474dc3cb4STobias Grosser   }
240574dc3cb4STobias Grosser 
240674dc3cb4STobias Grosser   PM.run(*GPUModule);
240774dc3cb4STobias Grosser 
24081a53b732SMichael Kruse   return ASMStream.str().str();
240974dc3cb4STobias Grosser }
241074dc3cb4STobias Grosser 
24118fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
24125b307cdbSTobias Grosser   bool RequiresLibDevice = false;
24138fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
24148fc6cdfbSTobias Grosser     if (!F.isDeclaration())
24158fc6cdfbSTobias Grosser       continue;
24168fc6cdfbSTobias Grosser 
241766a05ad6SPhilip Pfaffe     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
24188fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
241956572c6aSSiddharth Bhat       // We need to handle the case where a module looks like this:
242056572c6aSSiddharth Bhat       // @expf(..)
242156572c6aSSiddharth Bhat       // @llvm.exp.f64(..)
242256572c6aSSiddharth Bhat       // Both of these functions would be renamed to `__nv_expf`.
242356572c6aSSiddharth Bhat       //
242456572c6aSSiddharth Bhat       // So, we must first check for the existence of the libdevice function.
242556572c6aSSiddharth Bhat       // If this exists, we replace our current function with it.
242656572c6aSSiddharth Bhat       //
242756572c6aSSiddharth Bhat       // If it does not exist, we rename the current function to the
242856572c6aSSiddharth Bhat       // libdevice functiono name.
242956572c6aSSiddharth Bhat       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
243056572c6aSSiddharth Bhat         F.replaceAllUsesWith(Replacement);
243156572c6aSSiddharth Bhat       else
24328fc6cdfbSTobias Grosser         F.setName(CUDALibDeviceFunc);
24335b307cdbSTobias Grosser       RequiresLibDevice = true;
24348fc6cdfbSTobias Grosser     }
24358fc6cdfbSTobias Grosser   }
24368fc6cdfbSTobias Grosser 
24375b307cdbSTobias Grosser   return RequiresLibDevice;
24388fc6cdfbSTobias Grosser }
24398fc6cdfbSTobias Grosser 
24408fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
24418fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
24428fc6cdfbSTobias Grosser     return;
24438fc6cdfbSTobias Grosser 
24448fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
24458fc6cdfbSTobias Grosser     SMDiagnostic Error;
24468fc6cdfbSTobias Grosser 
24478fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
24488fc6cdfbSTobias Grosser     auto LibDeviceModule =
24498fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
24508fc6cdfbSTobias Grosser 
24518fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
24528fc6cdfbSTobias Grosser       BuildSuccessful = false;
24538fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
24548fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
24558fc6cdfbSTobias Grosser                          "accordingly.\n");
24568fc6cdfbSTobias Grosser       return;
24578fc6cdfbSTobias Grosser     }
24588fc6cdfbSTobias Grosser 
24598fc6cdfbSTobias Grosser     Linker L(*GPUModule);
24608fc6cdfbSTobias Grosser 
24618fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
24628fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
24638fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
24648fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
24658fc6cdfbSTobias Grosser   }
24668fc6cdfbSTobias Grosser }
24678fc6cdfbSTobias Grosser 
246857793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
246965d7f72fSSiddharth Bhat 
24705857b701STobias Grosser   if (verifyModule(*GPUModule)) {
2471349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
247265d7f72fSSiddharth Bhat                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2473349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2474a0fb8b23SSiddharth Bhat                verifyModule(*GPUModule, &dbgs()););
247565d7f72fSSiddharth Bhat 
247665d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
247765d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
247865d7f72fSSiddharth Bhat 
24795857b701STobias Grosser     BuildSuccessful = false;
24805857b701STobias Grosser     return "";
24815857b701STobias Grosser   }
248232837fe3STobias Grosser 
24838fc6cdfbSTobias Grosser   addCUDALibDevice();
24848fc6cdfbSTobias Grosser 
248532837fe3STobias Grosser   if (DumpKernelIR)
248632837fe3STobias Grosser     outs() << *GPUModule << "\n";
248732837fe3STobias Grosser 
24882f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
24899a18d559STobias Grosser     // Optimize module.
24909a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
24919a18d559STobias Grosser     PassManagerBuilder PassBuilder;
24929a18d559STobias Grosser     PassBuilder.OptLevel = 3;
24939a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
24949a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
24959a18d559STobias Grosser     OptPasses.run(*GPUModule);
24962f3073b5SPhilipp Schaad   }
24979a18d559STobias Grosser 
249874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
249974dc3cb4STobias Grosser 
250074dc3cb4STobias Grosser   if (DumpKernelASM)
250174dc3cb4STobias Grosser     outs() << Assembly << "\n";
250274dc3cb4STobias Grosser 
250332837fe3STobias Grosser   GPUModule.release();
2504472f9654STobias Grosser   KernelIDs.clear();
250557793596STobias Grosser 
250657793596STobias Grosser   return Assembly;
250732837fe3STobias Grosser }
2508eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2509eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2510eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2511eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2512eadf76d3SSiddharth Bhat ///
2513eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2514eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2515eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2516eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2517eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2518eadf76d3SSiddharth Bhat 
2519eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2520eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2521eadf76d3SSiddharth Bhat   }
2522eadf76d3SSiddharth Bhat   return List;
2523eadf76d3SSiddharth Bhat }
2524eadf76d3SSiddharth Bhat 
2525eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2526eadf76d3SSiddharth Bhat ///
2527eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2528eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2529eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2530eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2531eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2532eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2533eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2534eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2535eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2536eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2537eadf76d3SSiddharth Bhat ///                  affines.
2538eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2539eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2540eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2541eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2542eadf76d3SSiddharth Bhat 
2543eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2544eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2545eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2546eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2547eadf76d3SSiddharth Bhat   }
2548eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2549eadf76d3SSiddharth Bhat 
2550eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2551eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2552eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2553eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2554eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2555eadf76d3SSiddharth Bhat   }
2556eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2557eadf76d3SSiddharth Bhat }
255832837fe3STobias Grosser 
25599dfe4e7cSTobias Grosser namespace {
25609dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
25619dfe4e7cSTobias Grosser public:
25629dfe4e7cSTobias Grosser   static char ID;
25639dfe4e7cSTobias Grosser 
256417f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
256517f01968SSiddharth Bhat 
256617f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
256717f01968SSiddharth Bhat 
2568e938517eSTobias Grosser   /// The scop that is currently processed.
2569e938517eSTobias Grosser   Scop *S;
2570e938517eSTobias Grosser 
257138fc0aedSTobias Grosser   LoopInfo *LI;
257238fc0aedSTobias Grosser   DominatorTree *DT;
257338fc0aedSTobias Grosser   ScalarEvolution *SE;
257438fc0aedSTobias Grosser   const DataLayout *DL;
257538fc0aedSTobias Grosser   RegionInfo *RI;
257638fc0aedSTobias Grosser 
25773dcb5351SMichael Kruse   PPCGCodeGeneration() : ScopPass(ID) {
25783dcb5351SMichael Kruse     // Apply defaults.
25793dcb5351SMichael Kruse     Runtime = GPURuntimeChoice;
25803dcb5351SMichael Kruse     Architecture = GPUArchChoice;
25813dcb5351SMichael Kruse   }
25829dfe4e7cSTobias Grosser 
2583e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2584e938517eSTobias Grosser   ///
2585e938517eSTobias Grosser   /// @returns The compilation options.
2586e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2587e938517eSTobias Grosser     auto DebugOptions =
2588e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2589e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2590e938517eSTobias Grosser 
2591e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2592e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2593e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2594e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
25958950ceadSTobias Grosser     DebugOptions->verbose = false;
2596e938517eSTobias Grosser 
2597e938517eSTobias Grosser     Options->debug = DebugOptions;
2598e938517eSTobias Grosser 
25999e3db2b7SSiddharth Bhat     Options->group_chains = false;
2600e938517eSTobias Grosser     Options->reschedule = true;
2601e938517eSTobias Grosser     Options->scale_tile_loops = false;
2602e938517eSTobias Grosser     Options->wrap = false;
2603e938517eSTobias Grosser 
2604e938517eSTobias Grosser     Options->non_negative_parameters = false;
2605e938517eSTobias Grosser     Options->ctx = nullptr;
2606e938517eSTobias Grosser     Options->sizes = nullptr;
2607e938517eSTobias Grosser 
26089e3db2b7SSiddharth Bhat     Options->tile = true;
26094eaedde5STobias Grosser     Options->tile_size = 32;
26104eaedde5STobias Grosser 
26119e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
26129e3db2b7SSiddharth Bhat 
2613130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2614b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2615b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2616e938517eSTobias Grosser 
2617e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2618e938517eSTobias Grosser     Options->openmp = false;
2619e938517eSTobias Grosser     Options->linearize_device_arrays = true;
26209e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2621e938517eSTobias Grosser 
26229e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
26239e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
26249e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26259e3db2b7SSiddharth Bhat 
26269e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26279e3db2b7SSiddharth Bhat     Options->hybrid = false;
2628e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2629e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2630e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2631e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2632e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2633e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2634e938517eSTobias Grosser 
2635e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2636e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2637e938517eSTobias Grosser 
2638e938517eSTobias Grosser     return Options;
2639e938517eSTobias Grosser   }
2640e938517eSTobias Grosser 
2641f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2642f384594dSTobias Grosser   ///
2643f384594dSTobias Grosser   /// Instead of a normal access of the form:
2644f384594dSTobias Grosser   ///
2645f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2646f384594dSTobias Grosser   ///
2647f384594dSTobias Grosser   /// a tagged access has the form
2648f384594dSTobias Grosser   ///
2649f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2650f384594dSTobias Grosser   ///
2651f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2652f384594dSTobias Grosser   /// triggered the access.
2653f384594dSTobias Grosser   ///
2654f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2655f384594dSTobias Grosser   ///
2656f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2657f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2658b65ccc43STobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2659f384594dSTobias Grosser 
2660f384594dSTobias Grosser     for (auto &Stmt : *S)
2661f384594dSTobias Grosser       for (auto &Acc : Stmt)
2662f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
26631515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2664dcf8d696STobias Grosser           Relation =
2665dcf8d696STobias Grosser               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2666f384594dSTobias Grosser 
2667f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2668f384594dSTobias Grosser           Space = isl_space_range(Space);
2669f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2670fe46c3ffSTobias Grosser           Space =
2671fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2672f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2673f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2674f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2675f384594dSTobias Grosser         }
2676f384594dSTobias Grosser 
2677f384594dSTobias Grosser     return Accesses;
2678f384594dSTobias Grosser   }
2679f384594dSTobias Grosser 
2680f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2681f384594dSTobias Grosser   ///
2682f384594dSTobias Grosser   /// @see getTaggedAccesses
2683f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2684f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2685f384594dSTobias Grosser   }
2686f384594dSTobias Grosser 
2687f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2688f384594dSTobias Grosser   ///
2689f384594dSTobias Grosser   /// @see getTaggedAccesses
2690f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2691f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2692f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2693f384594dSTobias Grosser   }
2694f384594dSTobias Grosser 
2695f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2696f384594dSTobias Grosser   ///
2697f384594dSTobias Grosser   /// @see getTaggedAccesses
2698f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2699f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2700f384594dSTobias Grosser   }
2701f384594dSTobias Grosser 
2702aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2703aef5196fSTobias Grosser   ///
2704aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2705aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2706aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2707aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2708aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2709aef5196fSTobias Grosser   /// the data format that ppcg expects.
2710aef5196fSTobias Grosser   ///
2711aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2712aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2713aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
271400fd43b3SPhilip Pfaffe         S->getIslCtx().get(),
2715bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
271600fd43b3SPhilip Pfaffe     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2717aef5196fSTobias Grosser 
271825271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
27199a63570bSTobias Grosser       isl_id *Id = S->getIdForParam(P).release();
2720aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2721aef5196fSTobias Grosser     }
2722aef5196fSTobias Grosser 
2723aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
272477eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2725aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2726aef5196fSTobias Grosser     }
2727aef5196fSTobias Grosser 
2728aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2729aef5196fSTobias Grosser 
2730aef5196fSTobias Grosser     return Names;
2731aef5196fSTobias Grosser   }
2732aef5196fSTobias Grosser 
2733e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2734e938517eSTobias Grosser   ///
2735f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2736f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2737f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2738f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2739e938517eSTobias Grosser   ///
2740e938517eSTobias Grosser   /// @returns A new ppcg scop.
2741e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
27429e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
27439e3db2b7SSiddharth Bhat 
2744e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2745e938517eSTobias Grosser 
2746e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2747a82f2d26SSiddharth Bhat     // enable live range reordering
2748a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2749e938517eSTobias Grosser 
2750e938517eSTobias Grosser     PPCGScop->start = 0;
2751e938517eSTobias Grosser     PPCGScop->end = 0;
2752e938517eSTobias Grosser 
27538ea1fc19STobias Grosser     PPCGScop->context = S->getContext().release();
275431df6f31STobias Grosser     PPCGScop->domain = S->getDomains().release();
27559e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
27568ea1fc19STobias Grosser     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2757f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
27585ab39ff2STobias Grosser     PPCGScop->reads = S->getReads().release();
2759e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2760f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
27615ab39ff2STobias Grosser     PPCGScop->may_writes = S->getWrites().release();
2762f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
27635ab39ff2STobias Grosser     PPCGScop->must_writes = S->getMustWrites().release();
2764e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
27658dae41a1STobias Grosser     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
27668dae41a1STobias Grosser     PPCGScop->must_kills = KillsInfo.MustKills.release();
27679e3db2b7SSiddharth Bhat 
2768e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2769a82f2d26SSiddharth Bhat     PPCGScop->independence =
2770a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2771e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2772e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2773e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2774e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2775e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2776e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2777e938517eSTobias Grosser 
277861bd3a48STobias Grosser     PPCGScop->schedule = S->getScheduleTree().release();
2779a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2780a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2781a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
27828dae41a1STobias Grosser           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2783a82f2d26SSiddharth Bhat 
2784a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2785e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2786e938517eSTobias Grosser 
2787f384594dSTobias Grosser     compute_tagger(PPCGScop);
2788f384594dSTobias Grosser     compute_dependences(PPCGScop);
27899e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2790f384594dSTobias Grosser 
2791e938517eSTobias Grosser     return PPCGScop;
2792e938517eSTobias Grosser   }
2793e938517eSTobias Grosser 
2794a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
279560f63b49STobias Grosser   ///
279660f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
279760f63b49STobias Grosser   ///
279860f63b49STobias Grosser   /// @returns A list of array accesses.
279960f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
280060f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
280160f63b49STobias Grosser 
280260f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
280300fd43b3SPhilip Pfaffe       auto Access =
280400fd43b3SPhilip Pfaffe           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
280560f63b49STobias Grosser       Access->read = Acc->isRead();
280660f63b49STobias Grosser       Access->write = Acc->isWrite();
28071515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
280860f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
280960f63b49STobias Grosser       Space = isl_space_range(Space);
281060f63b49STobias Grosser       Space = isl_space_from_range(Space);
2811fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
281260f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
281360f63b49STobias Grosser       Access->tagged_access =
28141515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2815b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2816fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
281760f63b49STobias Grosser       Access->next = Accesses;
2818b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2819ecb94a03STobias Grosser       // TODO: Also mark one-element accesses to arrays as fixed-element.
2820ecb94a03STobias Grosser       Access->fixed_element =
2821ecb94a03STobias Grosser           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
282260f63b49STobias Grosser       Accesses = Access;
282360f63b49STobias Grosser     }
282460f63b49STobias Grosser 
282560f63b49STobias Grosser     return Accesses;
282660f63b49STobias Grosser   }
282760f63b49STobias Grosser 
282869b46751STobias Grosser   /// Collect the list of GPU statements.
282969b46751STobias Grosser   ///
283069b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
283169b46751STobias Grosser   /// as well as a list with all memory accesses.
283269b46751STobias Grosser   ///
283369b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
283469b46751STobias Grosser   ///
283569b46751STobias Grosser   /// @returns A linked-list of statements.
283669b46751STobias Grosser   gpu_stmt *getStatements() {
283700fd43b3SPhilip Pfaffe     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
283869b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
283969b46751STobias Grosser 
284069b46751STobias Grosser     int i = 0;
284169b46751STobias Grosser     for (auto &Stmt : *S) {
284269b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
284369b46751STobias Grosser 
2844dcf8d696STobias Grosser       GPUStmt->id = Stmt.getDomainId().release();
284569b46751STobias Grosser 
284669b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
284769b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
284860f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
284969b46751STobias Grosser       i++;
285069b46751STobias Grosser     }
285169b46751STobias Grosser 
285269b46751STobias Grosser     return Stmts;
285369b46751STobias Grosser   }
285469b46751STobias Grosser 
285560f63b49STobias Grosser   /// Derive the extent of an array.
285660f63b49STobias Grosser   ///
2857d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2858d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2859d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2860d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2861d58acf86STobias Grosser   /// subscript value for the first dimension.
286260f63b49STobias Grosser   ///
286360f63b49STobias Grosser   /// @param Array The array to derive the extent for.
286460f63b49STobias Grosser   ///
286560f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
2866d2e57981STobias Grosser   isl::set getExtent(ScopArrayInfo *Array) {
2867d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
2868fa03cb76STobias Grosser 
2869fa03cb76STobias Grosser     if (Array->getNumberOfDimensions() == 0)
2870fa03cb76STobias Grosser       return isl::set::universe(Array->getSpace());
2871fa03cb76STobias Grosser 
2872fa03cb76STobias Grosser     isl::union_map Accesses = S->getAccesses(Array);
2873d2e57981STobias Grosser     isl::union_set AccessUSet = Accesses.range();
2874d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2875d2e57981STobias Grosser     AccessUSet = AccessUSet.detect_equalities();
2876d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2877d58acf86STobias Grosser 
2878d2e57981STobias Grosser     if (AccessUSet.is_empty())
2879d2e57981STobias Grosser       return isl::set::empty(Array->getSpace());
2880d58acf86STobias Grosser 
2881d2e57981STobias Grosser     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
288260f63b49STobias Grosser 
2883d2e57981STobias Grosser     isl::local_space LS = isl::local_space(Array->getSpace());
2884d58acf86STobias Grosser 
2885d2e57981STobias Grosser     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2886d2e57981STobias Grosser     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2887d2e57981STobias Grosser     isl::pw_aff OuterMax = AccessSet.dim_max(0);
2888d2e57981STobias Grosser     OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2889d2e57981STobias Grosser     OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2890d2e57981STobias Grosser     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2891d2e57981STobias Grosser     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2892d58acf86STobias Grosser 
2893d2e57981STobias Grosser     isl::set Extent = isl::set::universe(Array->getSpace());
2894d58acf86STobias Grosser 
2895d2e57981STobias Grosser     Extent = Extent.intersect(OuterMin.le_set(Val));
2896d2e57981STobias Grosser     Extent = Extent.intersect(OuterMax.ge_set(Val));
2897d58acf86STobias Grosser 
2898d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2899d2e57981STobias Grosser       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2900d58acf86STobias Grosser 
2901b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2902d2e57981STobias Grosser       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2903b7f68b8cSSiddharth Bhat 
2904b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2905b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2906d2e57981STobias Grosser       if (PwAff.is_null()) {
2907b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2908b7f68b8cSSiddharth Bhat         continue;
2909b7f68b8cSSiddharth Bhat       }
2910b7f68b8cSSiddharth Bhat 
2911d2e57981STobias Grosser       isl::pw_aff Val = isl::aff::var_on_domain(
2912d2e57981STobias Grosser           isl::local_space(Array->getSpace()), isl::dim::set, i);
2913d2e57981STobias Grosser       PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2914d2e57981STobias Grosser       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2915d2e57981STobias Grosser       isl::set Set = PwAff.gt_set(Val);
2916d2e57981STobias Grosser       Extent = Set.intersect(Extent);
2917d58acf86STobias Grosser     }
2918d58acf86STobias Grosser 
2919d58acf86STobias Grosser     return Extent;
292060f63b49STobias Grosser   }
292160f63b49STobias Grosser 
292260f63b49STobias Grosser   /// Derive the bounds of an array.
292360f63b49STobias Grosser   ///
292460f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
292560f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
292660f63b49STobias Grosser   /// ScopArrayInfo.
292760f63b49STobias Grosser   ///
292860f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
292960f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
293060f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2931eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
29329e3db2b7SSiddharth Bhat 
293360f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
293402293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
293502293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
293602293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
293702293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
293802293ed7STobias Grosser         isl_set_free(Dom);
29399e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2940eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
294102293ed7STobias Grosser       } else {
294260f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
294360f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
294460f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
294560f63b49STobias Grosser         isl_set_free(Dom);
294660f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
294702293ed7STobias Grosser         isl_local_space *LS =
294802293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
294960f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
295060f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
295160f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
29528ea1fc19STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2953eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
295460f63b49STobias Grosser       }
295502293ed7STobias Grosser     }
295660f63b49STobias Grosser 
295760f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
295877eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
295960f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
296060f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
2961e2950f46SSiddharth Bhat 
2962e2950f46SSiddharth Bhat       // We need types to work out, which is why we perform this weird dance
2963e2950f46SSiddharth Bhat       // with `Aff` and `Bound`. Consider this example:
2964e2950f46SSiddharth Bhat 
2965e2950f46SSiddharth Bhat       // LS: [p] -> { [] }
2966e2950f46SSiddharth Bhat       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2967e2950f46SSiddharth Bhat       // This `~` is used to denote a "null space" (which is different from
2968e2950f46SSiddharth Bhat       // a *zero dimensional* space), which is something that ISL does not
2969e2950f46SSiddharth Bhat       // show you when pretty printing.
2970e2950f46SSiddharth Bhat 
2971e2950f46SSiddharth Bhat       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2972e2950f46SSiddharth Bhat       // space, not a "null space" which does not exist at all.
2973e2950f46SSiddharth Bhat 
2974e2950f46SSiddharth Bhat       // When we pullback (precompose) `Bound` with `Zero`, we get:
2975e2950f46SSiddharth Bhat       // Bound . Zero =
2976e2950f46SSiddharth Bhat       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2977e2950f46SSiddharth Bhat       //     [p] -> { ~ -> [(10p)] } =
2978e2950f46SSiddharth Bhat       //     [p] -> [(10p)] (as ISL pretty prints it)
2979e2950f46SSiddharth Bhat       // Bound Pullback: [p] -> { [(10p)] }
2980e2950f46SSiddharth Bhat 
2981e2950f46SSiddharth Bhat       // We want this kind of an expression for Bound, without a
2982e2950f46SSiddharth Bhat       // zero dimensional input, but with a "null space" input for the types
2983e2950f46SSiddharth Bhat       // to work out later on, as far as I (Siddharth Bhat) understand.
2984e2950f46SSiddharth Bhat       // I was unable to find a reference to this in the ISL manual.
2985e2950f46SSiddharth Bhat       // References: Tobias Grosser.
2986e2950f46SSiddharth Bhat 
298760f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2988eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
298960f63b49STobias Grosser     }
29909e3db2b7SSiddharth Bhat 
2991eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2992eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2993eadf76d3SSiddharth Bhat     /// appropriate space.
2994eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2995eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2996eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2997eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2998b65ccc43STobias Grosser     isl_space *SeedAlignSpace = S->getParamSpace().release();
2999eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
3000eadf76d3SSiddharth Bhat 
3001eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
3002eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
3003eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
3004eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
3005eadf76d3SSiddharth Bhat 
3006eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
3007eadf76d3SSiddharth Bhat 
3008eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
300900fd43b3SPhilip Pfaffe         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
3010eadf76d3SSiddharth Bhat 
30119e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
3012eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
30139e3db2b7SSiddharth Bhat 
30149e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
30159e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
30169e3db2b7SSiddharth Bhat 
30179e3db2b7SSiddharth Bhat     PPCGArray.bound =
30189e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
30199e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
302060f63b49STobias Grosser   }
302160f63b49STobias Grosser 
302260f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
302360f63b49STobias Grosser   ///
302460f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
302543f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
302643f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
302760f63b49STobias Grosser     int i = 0;
302843f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
302960f63b49STobias Grosser       std::string TypeName;
303060f63b49STobias Grosser       raw_string_ostream OS(TypeName);
303160f63b49STobias Grosser 
303260f63b49STobias Grosser       OS << *Array->getElementType();
303360f63b49STobias Grosser       TypeName = OS.str();
303460f63b49STobias Grosser 
303560f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
303660f63b49STobias Grosser 
303777eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
303860f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
303934eeabbcSSiddharth Bhat       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
304060f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
304160f63b49STobias Grosser       PPCGArray.extent = nullptr;
304260f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
3043d2e57981STobias Grosser       PPCGArray.extent = getExtent(Array).release();
304460f63b49STobias Grosser       PPCGArray.n_ref = 0;
304560f63b49STobias Grosser       PPCGArray.refs = nullptr;
304660f63b49STobias Grosser       PPCGArray.accessed = true;
3047fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
3048fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
304960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
305060f63b49STobias Grosser       PPCGArray.local = false;
305160f63b49STobias Grosser       PPCGArray.declare_local = false;
305260f63b49STobias Grosser       PPCGArray.global = false;
305360f63b49STobias Grosser       PPCGArray.linearize = false;
305460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
305513c78e4dSTobias Grosser       PPCGArray.user = Array;
305660f63b49STobias Grosser 
30579e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
305860f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
30592d010dafSTobias Grosser       i++;
3060b9fc860aSTobias Grosser 
3061b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
3062ecb94a03STobias Grosser       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
306360f63b49STobias Grosser     }
306460f63b49STobias Grosser   }
306560f63b49STobias Grosser 
306660f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
306760f63b49STobias Grosser   ///
306860f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
306960f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
3070b65ccc43STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
307160f63b49STobias Grosser 
3072d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
307377eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
307460f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
307560f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
307660f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
307760f63b49STobias Grosser     }
307860f63b49STobias Grosser 
307960f63b49STobias Grosser     return Maps;
308060f63b49STobias Grosser   }
308160f63b49STobias Grosser 
3082e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
3083e938517eSTobias Grosser   ///
3084a6d48f59SMichael Kruse   /// @returns A new gpu program description.
3085e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3086e938517eSTobias Grosser 
3087e938517eSTobias Grosser     if (!PPCGScop)
3088e938517eSTobias Grosser       return nullptr;
3089e938517eSTobias Grosser 
309000fd43b3SPhilip Pfaffe     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3091e938517eSTobias Grosser 
309200fd43b3SPhilip Pfaffe     PPCGProg->ctx = S->getIslCtx().get();
3093e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
3094aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
309560f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
309660f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
309760f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
309860f63b49STobias Grosser     PPCGProg->tagged_must_kill =
309960f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
310060f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
310160f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
31029e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
3103e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
310469b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
310569b46751STobias Grosser     PPCGProg->stmts = getStatements();
310643f178bbSSiddharth Bhat 
310743f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
310843f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
310943f178bbSSiddharth Bhat     // empty arrays:
311043f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
311143f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
311243f178bbSSiddharth Bhat     auto ValidSAIsRange =
311343f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3114d2e57981STobias Grosser           return !getExtent(SAI).is_empty();
311543f178bbSSiddharth Bhat         });
311643f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
311743f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
311843f178bbSSiddharth Bhat 
311943f178bbSSiddharth Bhat     PPCGProg->n_array =
312043f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
312158166b13SMichael Kruse     PPCGProg->array = isl_calloc_array(
312258166b13SMichael Kruse         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
312360f63b49STobias Grosser 
312443f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
3125e938517eSTobias Grosser 
3126ecb94a03STobias Grosser     PPCGProg->array_order = nullptr;
3127ecb94a03STobias Grosser     collect_order_dependences(PPCGProg);
3128ecb94a03STobias Grosser 
3129d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3130e938517eSTobias Grosser     return PPCGProg;
3131e938517eSTobias Grosser   }
3132e938517eSTobias Grosser 
313369b46751STobias Grosser   struct PrintGPUUserData {
313469b46751STobias Grosser     struct cuda_info *CudaInfo;
313569b46751STobias Grosser     struct gpu_prog *PPCGProg;
313669b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
313769b46751STobias Grosser   };
313869b46751STobias Grosser 
313969b46751STobias Grosser   /// Print a user statement node in the host code.
314069b46751STobias Grosser   ///
314169b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
314269b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
314369b46751STobias Grosser   /// host ast.
314469b46751STobias Grosser   ///
314569b46751STobias Grosser   /// @param P The printer to print to
314669b46751STobias Grosser   /// @param Options The printing options to use
314769b46751STobias Grosser   /// @param Node The node to print
314869b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
314969b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
315069b46751STobias Grosser   ///
315169b46751STobias Grosser   /// @returns A printer to which the output has been printed.
315269b46751STobias Grosser   static __isl_give isl_printer *
315369b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
315469b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
315569b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
315669b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
315769b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
315869b46751STobias Grosser 
315969b46751STobias Grosser     if (Id) {
316020251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
316120251734STobias Grosser 
316220251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
316320251734STobias Grosser       // otherwise try to call pet functionality that is not available in
316420251734STobias Grosser       // Polly.
316520251734STobias Grosser       if (IsUser) {
316620251734STobias Grosser         P = isl_printer_start_line(P);
316720251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
316820251734STobias Grosser         P = isl_printer_end_line(P);
316920251734STobias Grosser         isl_id_free(Id);
317020251734STobias Grosser         isl_ast_print_options_free(Options);
317120251734STobias Grosser         return P;
317220251734STobias Grosser       }
317320251734STobias Grosser 
317469b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
317569b46751STobias Grosser       isl_id_free(Id);
317669b46751STobias Grosser       Data->Kernels.push_back(Kernel);
317769b46751STobias Grosser     }
317869b46751STobias Grosser 
317969b46751STobias Grosser     return print_host_user(P, Options, Node, User);
318069b46751STobias Grosser   }
318169b46751STobias Grosser 
318269b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
318369b46751STobias Grosser   ///
318469b46751STobias Grosser   /// @param Kernel The kernel to print
318569b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
318600fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
318769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
318800fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
318969b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
319069b46751STobias Grosser     char *String = isl_printer_get_str(P);
3191936c74adSSiddharth Bhat     outs() << String << "\n";
319269b46751STobias Grosser     free(String);
319369b46751STobias Grosser     isl_printer_free(P);
319469b46751STobias Grosser   }
319569b46751STobias Grosser 
319669b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
319769b46751STobias Grosser   ///
319869b46751STobias Grosser   /// @param Tree An AST describing GPU code
319969b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
320069b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
320100fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
320269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
320369b46751STobias Grosser 
320469b46751STobias Grosser     PrintGPUUserData Data;
320569b46751STobias Grosser     Data.PPCGProg = PPCGProg;
320669b46751STobias Grosser 
320700fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
320869b46751STobias Grosser     Options =
320969b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
321069b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
321169b46751STobias Grosser     char *String = isl_printer_get_str(P);
3212936c74adSSiddharth Bhat     outs() << "# host\n";
3213936c74adSSiddharth Bhat     outs() << String << "\n";
321469b46751STobias Grosser     free(String);
321569b46751STobias Grosser     isl_printer_free(P);
321669b46751STobias Grosser 
321769b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
3218936c74adSSiddharth Bhat       outs() << "# kernel" << Kernel->id << "\n";
321969b46751STobias Grosser       printKernel(Kernel);
322069b46751STobias Grosser     }
322169b46751STobias Grosser   }
322269b46751STobias Grosser 
3223f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3224f384594dSTobias Grosser   //
3225f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3226f384594dSTobias Grosser   //
3227f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3228f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3229f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3230f384594dSTobias Grosser   //
3231f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3232f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3233f384594dSTobias Grosser   // strategy directly from this pass.
3234f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3235f384594dSTobias Grosser 
323600fd43b3SPhilip Pfaffe     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3237f384594dSTobias Grosser 
323800fd43b3SPhilip Pfaffe     PPCGGen->ctx = S->getIslCtx().get();
3239f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3240f384594dSTobias Grosser     PPCGGen->print = nullptr;
3241f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
324260c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3243f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3244f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3245f384594dSTobias Grosser     PPCGGen->types.n = 0;
3246f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3247f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3248f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3249f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3250f384594dSTobias Grosser 
3251f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3252f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3253f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
32542341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3255f384594dSTobias Grosser 
3256f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3257f384594dSTobias Grosser 
3258e32498c9STobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3259e32498c9STobias Grosser 
3260b5563c68STobias Grosser     Schedule =
3261b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3262b5563c68STobias Grosser 
326369b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3264aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3265349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3266638316daSSiddharth Bhat                         << " does not have permutable bands. Bailing out\n";);
326769b46751STobias Grosser     } else {
3268861a387fSTobias Grosser       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3269861a387fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
327069b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
327169b46751STobias Grosser     }
3272aef5196fSTobias Grosser 
3273f384594dSTobias Grosser     if (DumpSchedule) {
327400fd43b3SPhilip Pfaffe       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3275f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3276f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3277f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3278f384594dSTobias Grosser       if (Schedule)
3279f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3280f384594dSTobias Grosser       else
3281f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3282f384594dSTobias Grosser 
3283936c74adSSiddharth Bhat       outs() << isl_printer_get_str(P) << "\n";
3284f384594dSTobias Grosser       isl_printer_free(P);
3285f384594dSTobias Grosser     }
3286f384594dSTobias Grosser 
328769b46751STobias Grosser     if (DumpCode) {
3288936c74adSSiddharth Bhat       outs() << "Code\n";
3289936c74adSSiddharth Bhat       outs() << "====\n";
329069b46751STobias Grosser       if (PPCGGen->tree)
329169b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
329269b46751STobias Grosser       else
3293936c74adSSiddharth Bhat         outs() << "No code generated\n";
329469b46751STobias Grosser     }
329569b46751STobias Grosser 
3296f384594dSTobias Grosser     isl_schedule_free(Schedule);
3297f384594dSTobias Grosser 
3298f384594dSTobias Grosser     return PPCGGen;
3299f384594dSTobias Grosser   }
3300f384594dSTobias Grosser 
3301f384594dSTobias Grosser   /// Free gpu_gen structure.
3302f384594dSTobias Grosser   ///
3303f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3304f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3305f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3306f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3307f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3308f384594dSTobias Grosser     free(PPCGGen);
3309f384594dSTobias Grosser   }
3310f384594dSTobias Grosser 
3311b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3312b307ed4dSTobias Grosser   ///
3313b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3314b307ed4dSTobias Grosser   /// ourselves.
3315b307ed4dSTobias Grosser   ///
3316b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3317b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3318b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3319b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3320b307ed4dSTobias Grosser     free(PPCGScop->options);
3321b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3322b307ed4dSTobias Grosser   }
3323b307ed4dSTobias Grosser 
332482f2af35STobias Grosser   /// Approximate the number of points in the set.
332582f2af35STobias Grosser   ///
332682f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
332782f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
332882f2af35STobias Grosser   ///
332982f2af35STobias Grosser   /// @param Set   The set to count.
333082f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
333182f2af35STobias Grosser   ///              expression.
333282f2af35STobias Grosser   ///
333382f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
333482f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
333582f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
333682f2af35STobias Grosser 
333782f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
333882f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
333982f2af35STobias Grosser 
334082f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
334182f2af35STobias Grosser     Space = isl_space_params(Space);
334282f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
334382f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
334482f2af35STobias Grosser 
33453044dc51SMichael Kruse     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
334682f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
334782f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
334882f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
334982f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
335082f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
335182f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
335282f2af35STobias Grosser     }
335382f2af35STobias Grosser 
335482f2af35STobias Grosser     isl_set_free(Set);
335582f2af35STobias Grosser     isl_pw_aff_free(OneAff);
335682f2af35STobias Grosser 
335782f2af35STobias Grosser     return Expr;
335882f2af35STobias Grosser   }
335982f2af35STobias Grosser 
336082f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
336182f2af35STobias Grosser   /// statement.
336282f2af35STobias Grosser   ///
336382f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
336482f2af35STobias Grosser   ///              instructions.
336582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
336682f2af35STobias Grosser   ///              expression.
336782f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
336882f2af35STobias Grosser   ///          by @p Stmt.
336982f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
337082f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
3371dcf8d696STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
337282f2af35STobias Grosser 
337382f2af35STobias Grosser     long InstCount = 0;
337482f2af35STobias Grosser 
337582f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
337682f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
337782f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
337882f2af35STobias Grosser     } else {
337982f2af35STobias Grosser       auto *R = Stmt.getRegion();
338082f2af35STobias Grosser 
338182f2af35STobias Grosser       for (auto *BB : R->blocks()) {
338282f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
338382f2af35STobias Grosser       }
338482f2af35STobias Grosser     }
338582f2af35STobias Grosser 
338600fd43b3SPhilip Pfaffe     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
338782f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
338882f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
338982f2af35STobias Grosser   }
339082f2af35STobias Grosser 
339182f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
339282f2af35STobias Grosser   ///
339382f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
339482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
339582f2af35STobias Grosser   ///              expression.
339682f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
339782f2af35STobias Grosser   ///          in @p S.
339882f2af35STobias Grosser   __isl_give isl_ast_expr *
339982f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
340082f2af35STobias Grosser     isl_ast_expr *Instructions;
340182f2af35STobias Grosser 
340200fd43b3SPhilip Pfaffe     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
340382f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
340482f2af35STobias Grosser 
340582f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
340682f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
340782f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
340882f2af35STobias Grosser     }
340982f2af35STobias Grosser     return Instructions;
341082f2af35STobias Grosser   }
341182f2af35STobias Grosser 
341282f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
341382f2af35STobias Grosser   ///
341482f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
341582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
341682f2af35STobias Grosser   ///              expression.
341782f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
341882f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
341982f2af35STobias Grosser   __isl_give isl_ast_expr *
342082f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
342182f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
342200fd43b3SPhilip Pfaffe     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
342382f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
342482f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
342582f2af35STobias Grosser   }
342682f2af35STobias Grosser 
3427f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3428f291c8d5SSiddharth Bhat   /// kernels.
3429f291c8d5SSiddharth Bhat   ///
3430f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3431f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
34328fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
34338fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3434f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3435f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
34368fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
343778027437SSiddharth Bhat                                           AllowCUDALibDevice))
3438f291c8d5SSiddharth Bhat         continue;
3439f291c8d5SSiddharth Bhat 
344078027437SSiddharth Bhat       for (Value *Op : Inst.operands())
344178027437SSiddharth Bhat         // Look for (<func-type>*) among operands of Inst
344278027437SSiddharth Bhat         if (auto PtrTy = dyn_cast<PointerType>(Op->getType())) {
344378027437SSiddharth Bhat           if (isa<FunctionType>(PtrTy->getElementType())) {
3444349506a9SNicola Zaghen             LLVM_DEBUG(dbgs()
3445349506a9SNicola Zaghen                        << Inst << " has illegal use of function in kernel.\n");
3446bccaea57SSiddharth Bhat             return true;
3447bccaea57SSiddharth Bhat           }
3448f291c8d5SSiddharth Bhat         }
344978027437SSiddharth Bhat     }
3450bccaea57SSiddharth Bhat     return false;
3451bccaea57SSiddharth Bhat   }
3452bccaea57SSiddharth Bhat 
3453f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
34548fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3455bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3456bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
34578fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
34588fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3459bccaea57SSiddharth Bhat           return true;
3460bccaea57SSiddharth Bhat       } else {
3461bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3462bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3463bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
34648fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3465bccaea57SSiddharth Bhat             return true;
3466bccaea57SSiddharth Bhat       }
3467bccaea57SSiddharth Bhat     }
3468bccaea57SSiddharth Bhat     return false;
3469bccaea57SSiddharth Bhat   }
3470bccaea57SSiddharth Bhat 
347138fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
347238fc0aedSTobias Grosser   ///
347332837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
347432837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
347532837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
347638fc0aedSTobias Grosser     ScopAnnotator Annotator;
347738fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
347838fc0aedSTobias Grosser 
347938fc0aedSTobias Grosser     Region *R = &S->getRegion();
348038fc0aedSTobias Grosser 
348138fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
348238fc0aedSTobias Grosser 
348338fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
348438fc0aedSTobias Grosser 
348555cfb1fbSNikita Popov     PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(),
348655cfb1fbSNikita Popov                            IRInserter(Annotator));
348755cfb1fbSNikita Popov     Builder.SetInsertPoint(EnteringBB->getTerminator());
348838fc0aedSTobias Grosser 
348938fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
349038fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
349138fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
349238fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
349338fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
349438fc0aedSTobias Grosser     // code generating this scop.
349503346c27SSiddharth Bhat     BBPair StartExitBlocks;
349603346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
349703346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
34982d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3499256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
350038fc0aedSTobias Grosser 
350103346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
350203346c27SSiddharth Bhat 
35032d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
350417f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3505acf80064SEli Friedman 
350638fc0aedSTobias Grosser     // TODO: Handle LICM
350738fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
350838fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
3509cb1aef8dSTobias Grosser 
351000fd43b3SPhilip Pfaffe     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
35114170d6cdSpatacca     isl::ast_expr Condition =
35124170d6cdSpatacca         IslAst::buildRunCondition(*S, isl::manage_copy(Build));
351382f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
35144170d6cdSpatacca     Condition =
35154170d6cdSpatacca         isl::manage(isl_ast_expr_and(Condition.release(), SufficientCompute));
3516cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3517cb1aef8dSTobias Grosser 
35189e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
35199e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
352071dfb3ebSSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads()) {
35212fb847fbSTobias Grosser       // Patch the introduced branch condition to ensure that we always execute
35222fb847fbSTobias Grosser       // the original SCoP.
35232fb847fbSTobias Grosser       auto *FalseI1 = Builder.getFalse();
35242fb847fbSTobias Grosser       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
35252fb847fbSTobias Grosser       SplitBBTerm->setOperand(0, FalseI1);
35262fb847fbSTobias Grosser 
3527349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
35284ebeb356SSiddharth Bhat                                S->getFunction().getName() +
35294ebeb356SSiddharth Bhat                                " | Scop Region: " + S->getNameStr());
353071dfb3ebSSiddharth Bhat       // adjust the dominator tree accordingly.
353171dfb3ebSSiddharth Bhat       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
353271dfb3ebSSiddharth Bhat       assert(ExitingBlock);
353371dfb3ebSSiddharth Bhat       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
353471dfb3ebSSiddharth Bhat       assert(MergeBlock);
353571dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*StartBlock, Builder);
353671dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*ExitingBlock, Builder);
353771dfb3ebSSiddharth Bhat       auto *ExitingBB = S->getExitingBlock();
353871dfb3ebSSiddharth Bhat       assert(ExitingBB);
35399e3db2b7SSiddharth Bhat 
354071dfb3ebSSiddharth Bhat       DT->changeImmediateDominator(MergeBlock, ExitingBB);
354171dfb3ebSSiddharth Bhat       DT->eraseNode(ExitingBlock);
354271dfb3ebSSiddharth Bhat       isl_ast_node_free(Root);
354371dfb3ebSSiddharth Bhat     } else {
354471dfb3ebSSiddharth Bhat 
35457b9f5ca2SSiddharth Bhat       if (polly::PerfMonitoring) {
35467b9f5ca2SSiddharth Bhat         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
35477b9f5ca2SSiddharth Bhat         P.initialize();
35487b9f5ca2SSiddharth Bhat         P.insertRegionStart(SplitBlock->getTerminator());
35497b9f5ca2SSiddharth Bhat 
35507b9f5ca2SSiddharth Bhat         // TODO: actually think if this is the correct exiting block to place
35517b9f5ca2SSiddharth Bhat         // the `end` performance marker. Invariant load hoisting changes
35527b9f5ca2SSiddharth Bhat         // the CFG in a way that I do not precisely understand, so I
35537b9f5ca2SSiddharth Bhat         // (Siddharth<[email protected]>) should come back to this and
35547b9f5ca2SSiddharth Bhat         // think about which exiting block to use.
35557b9f5ca2SSiddharth Bhat         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
35567b9f5ca2SSiddharth Bhat         assert(ExitingBlock);
35577b9f5ca2SSiddharth Bhat         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
35587b9f5ca2SSiddharth Bhat         P.insertRegionEnd(MergeBlock->getTerminator());
35597b9f5ca2SSiddharth Bhat       }
35607b9f5ca2SSiddharth Bhat 
356171dfb3ebSSiddharth Bhat       NodeBuilder.addParameters(S->getContext().release());
35624170d6cdSpatacca       Value *RTC = NodeBuilder.createRTC(Condition.release());
3563cb1aef8dSTobias Grosser       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3564cb1aef8dSTobias Grosser 
356538fc0aedSTobias Grosser       Builder.SetInsertPoint(&*StartBlock->begin());
3566fa7b0802STobias Grosser 
356738fc0aedSTobias Grosser       NodeBuilder.create(Root);
356871dfb3ebSSiddharth Bhat     }
35695857b701STobias Grosser 
3570bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3571bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3572de244eb4STobias Grosser     /// point in running it on a GPU.
3573bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
357403346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3575bc653f20STobias Grosser 
35765857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
357703346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
357838fc0aedSTobias Grosser   }
357938fc0aedSTobias Grosser 
3580e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3581e938517eSTobias Grosser     S = &CurrentScop;
358238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
358338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
358438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
35857b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
358638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3587e938517eSTobias Grosser 
3588349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3589656e6295SSiddharth Bhat                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3590656e6295SSiddharth Bhat 
3591f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3592f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3593f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3594bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3595bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
35968fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
35978fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3598349506a9SNicola Zaghen       LLVM_DEBUG(
3599638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3600638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3601f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3602bccaea57SSiddharth Bhat       return false;
3603f291c8d5SSiddharth Bhat     }
3604bccaea57SSiddharth Bhat 
3605e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3606e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3607f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
360838fc0aedSTobias Grosser 
360902ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
361032837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
361102ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3612638316daSSiddharth Bhat     } else {
3613349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3614638316daSSiddharth Bhat                         << " has empty PPCGGen->tree. Bailing out.\n");
361502ca346eSSingapuram Sanjay Srivallabh     }
361638fc0aedSTobias Grosser 
3617b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3618f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3619e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3620e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3621e938517eSTobias Grosser 
3622e938517eSTobias Grosser     return true;
3623e938517eSTobias Grosser   }
36249dfe4e7cSTobias Grosser 
36259dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
36269dfe4e7cSTobias Grosser 
36279dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
3628a4f447c2SMichael Kruse     ScopPass::getAnalysisUsage(AU);
3629a4f447c2SMichael Kruse 
36309dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
36319dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
36329dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
36335cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
36349dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
36359dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
36369dfe4e7cSTobias Grosser 
36379dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
36389dfe4e7cSTobias Grosser     //        region tree.
36399dfe4e7cSTobias Grosser   }
36409dfe4e7cSTobias Grosser };
364124222c73STobias Grosser } // namespace
36429dfe4e7cSTobias Grosser 
36439dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
36449dfe4e7cSTobias Grosser 
364517f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
364617f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
364717f01968SSiddharth Bhat   generator->Runtime = Runtime;
364817f01968SSiddharth Bhat   generator->Architecture = Arch;
364917f01968SSiddharth Bhat   return generator;
365017f01968SSiddharth Bhat }
36519dfe4e7cSTobias Grosser 
36529dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
36539dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
36549dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
36559dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
36569dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
36579dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
36589dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
36595cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
36609dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
36619dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3662