19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
21f384594dSTobias Grosser #include "polly/Options.h"
22629109b6STobias Grosser #include "polly/ScopDetection.h"
239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
348fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
358fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
3674dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3774dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3874dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
399a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
40750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
419dfe4e7cSTobias Grosser 
42f384594dSTobias Grosser #include "isl/union_map.h"
43f384594dSTobias Grosser 
44e938517eSTobias Grosser extern "C" {
45a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
46a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
47a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
48a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
49a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
50e938517eSTobias Grosser }
51e938517eSTobias Grosser 
529dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
539dfe4e7cSTobias Grosser 
549dfe4e7cSTobias Grosser using namespace polly;
559dfe4e7cSTobias Grosser using namespace llvm;
569dfe4e7cSTobias Grosser 
579dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
589dfe4e7cSTobias Grosser 
59f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
60f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
61681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
62f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6369b46751STobias Grosser 
6469b46751STobias Grosser static cl::opt<bool>
6569b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6669b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6769b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6869b46751STobias Grosser 
6932837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
7032837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
7132837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7232837fe3STobias Grosser                                   cl::cat(PollyCategory));
7332837fe3STobias Grosser 
7474dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7574dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7674dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7774dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7874dc3cb4STobias Grosser 
7974dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
8074dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
8174dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8274dc3cb4STobias Grosser                               cl::cat(PollyCategory));
83b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
84b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
85b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
86b513b491STobias Grosser                                   cl::cat(PollyCategory));
87130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
88130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
89130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
90130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
9174dc3cb4STobias Grosser 
92abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
93abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
94abed4969SSiddharth Bhat                                             " that all memory has been"
95abed4969SSiddharth Bhat                                             " declared as managed memory"),
96abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
97abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
98abed4969SSiddharth Bhat 
9965d7f72fSSiddharth Bhat static cl::opt<bool>
10065d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
10165d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10265d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10365d7f72fSSiddharth Bhat                                        " kernel module."),
10465d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10565d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10665d7f72fSSiddharth Bhat 
1078fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1088fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1098fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1108fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1118fc6cdfbSTobias Grosser 
11274dc3cb4STobias Grosser static cl::opt<std::string>
11374dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11474dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11574dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
11674dc3cb4STobias Grosser 
11782f2af35STobias Grosser static cl::opt<int>
11882f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11982f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
12082f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
12182f2af35STobias Grosser 
122638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
123638316daSSiddharth Bhat /// function name.
124638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
125638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
126638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
127638316daSSiddharth Bhat }
128638316daSSiddharth Bhat 
129a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
130a82f2d26SSiddharth Bhat /// used by live range reordering.
131a82f2d26SSiddharth Bhat ///
132a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
133a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
134a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
135a82f2d26SSiddharth Bhat struct MustKillsInfo {
136a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
137a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
138a82f2d26SSiddharth Bhat   ///
139a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
140a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
141a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
142a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
143a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
144a82f2d26SSiddharth Bhat   /// killed.
145a82f2d26SSiddharth Bhat   ///
146edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
147edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
148edfef5aeSSiddharth Bhat   ///     consequently all be killed.
149edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
150edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
151edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
152a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
153a82f2d26SSiddharth Bhat 
1549e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1559e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1569e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1579e3db2b7SSiddharth Bhat 
1589e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
159a82f2d26SSiddharth Bhat };
160a82f2d26SSiddharth Bhat 
161761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
162761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
163761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
164761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
165761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
166761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
167761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
168761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
169761e5b93SSiddharth Bhat 
170761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
171761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
172761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
173761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
174761e5b93SSiddharth Bhat     if (!R.contains(I))
175761e5b93SSiddharth Bhat       return false;
176761e5b93SSiddharth Bhat   }
177761e5b93SSiddharth Bhat   return true;
178761e5b93SSiddharth Bhat }
179761e5b93SSiddharth Bhat 
180a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
181a82f2d26SSiddharth Bhat ///
182a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
183a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
184a82f2d26SSiddharth Bhat /// PPCG.
185a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
186a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
187a82f2d26SSiddharth Bhat   MustKillsInfo Info;
188a82f2d26SSiddharth Bhat 
189761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
190761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
191761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
192a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
193a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
194761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
195761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
19677eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
197a82f2d26SSiddharth Bhat   }
198a82f2d26SSiddharth Bhat 
199a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
2009e3db2b7SSiddharth Bhat   Info.MustKills = isl::union_map::empty(isl::space(ParamSpace));
201a82f2d26SSiddharth Bhat 
202a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
203a82f2d26SSiddharth Bhat   // schedule:
204a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
205a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
206a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
207a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
208a82f2d26SSiddharth Bhat 
209edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
210a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
211edfef5aeSSiddharth Bhat         S.getIslCtx(),
212edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
213a82f2d26SSiddharth Bhat 
214a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
215a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
216edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
217a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
218edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
219edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
220edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
221edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
222a82f2d26SSiddharth Bhat     //
223a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
224a82f2d26SSiddharth Bhat     // TaggedMustKill:
225edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
226a82f2d26SSiddharth Bhat 
227edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
228edfef5aeSSiddharth Bhat     isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace));
229edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
230edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
231a82f2d26SSiddharth Bhat 
232a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
233edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
234edfef5aeSSiddharth Bhat         nullptr);
235a82f2d26SSiddharth Bhat 
236edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
237edfef5aeSSiddharth Bhat     isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace));
238edfef5aeSSiddharth Bhat     PhantomRefToScalar =
239edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
240edfef5aeSSiddharth Bhat     PhantomRefToScalar =
241edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
242a82f2d26SSiddharth Bhat 
243edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
244edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
245a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
246a82f2d26SSiddharth Bhat 
2479e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2489e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2499e3db2b7SSiddharth Bhat 
250a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
251a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
252a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
253a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
254a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
255a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
256a82f2d26SSiddharth Bhat 
257a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
258a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
259a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
260a82f2d26SSiddharth Bhat     else
261a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
262a82f2d26SSiddharth Bhat   }
263a82f2d26SSiddharth Bhat 
264a82f2d26SSiddharth Bhat   return Info;
265a82f2d26SSiddharth Bhat }
266a82f2d26SSiddharth Bhat 
26760c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26860c60025STobias Grosser ///
26960c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
27060c60025STobias Grosser /// of the scheduled ScopStmts.
27160c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
27235de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
27360c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
27460c60025STobias Grosser                                        isl_id *Id, void *User),
27560c60025STobias Grosser     void *UserIndex,
27660c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
277edb885cbSTobias Grosser     void *UserExpr) {
27860c60025STobias Grosser 
279edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
28060c60025STobias Grosser 
28135de9009SSiddharth Bhat   if (!Stmt || !Build_C)
282edb885cbSTobias Grosser     return NULL;
283edb885cbSTobias Grosser 
28435de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
28535de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
28635de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
287edb885cbSTobias Grosser 
288edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
28935de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
29035de9009SSiddharth Bhat     AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain()));
29135de9009SSiddharth Bhat 
29235de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
29335de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
29435de9009SSiddharth Bhat 
29535de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
29635de9009SSiddharth Bhat     MPA = MPA.coalesce();
29735de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
29835de9009SSiddharth Bhat 
29935de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
30035de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
30135de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
302edb885cbSTobias Grosser   }
303edb885cbSTobias Grosser 
30435de9009SSiddharth Bhat   return RefToExpr.release();
30560c60025STobias Grosser }
306f384594dSTobias Grosser 
307a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
308a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
309a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
310a90be207SSiddharth Bhat   if (bytes == 0)
311a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
312a90be207SSiddharth Bhat   return bytes;
313a90be207SSiddharth Bhat }
314a90be207SSiddharth Bhat 
31538fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
31638fc0aedSTobias Grosser ///
31738fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
318a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
31938fc0aedSTobias Grosser /// for generating GPU specific user nodes.
32038fc0aedSTobias Grosser ///
32138fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
32238fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
32338fc0aedSTobias Grosser public:
3242d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
32538fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
326acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32717f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3282d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
32917f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
330edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
331edb885cbSTobias Grosser   }
33238fc0aedSTobias Grosser 
333fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
334fa7b0802STobias Grosser   void initializeAfterRTH();
335fa7b0802STobias Grosser 
336fa7b0802STobias Grosser   /// Finalize the generated scop.
337fa7b0802STobias Grosser   virtual void finalize();
338fa7b0802STobias Grosser 
3395857b701STobias Grosser   /// Track if the full build process was successful.
3405857b701STobias Grosser   ///
3415857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3425857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3435857b701STobias Grosser   bool BuildSuccessful = true;
3445857b701STobias Grosser 
345bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
346bc653f20STobias Grosser   unsigned DeepestSequential = 0;
347bc653f20STobias Grosser 
348bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
349bc653f20STobias Grosser   unsigned DeepestParallel = 0;
350bc653f20STobias Grosser 
35179f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
35279f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
35379f13b9aSSingapuram Sanjay Srivallabh 
35438fc0aedSTobias Grosser private:
35574dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
35674dc3cb4STobias Grosser   ///
35774dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
35874dc3cb4STobias Grosser   /// more.
35974dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
36074dc3cb4STobias Grosser 
36113c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
36213c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3637287aeddSTobias Grosser 
364fa7b0802STobias Grosser   /// The current GPU context.
365fa7b0802STobias Grosser   Value *GPUContext;
366fa7b0802STobias Grosser 
367b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
368b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
369b513b491STobias Grosser 
37032837fe3STobias Grosser   /// A module containing GPU code.
37132837fe3STobias Grosser   ///
37232837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
37332837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
37432837fe3STobias Grosser 
37532837fe3STobias Grosser   /// The GPU program we generate code for.
37632837fe3STobias Grosser   gpu_prog *Prog;
37732837fe3STobias Grosser 
37817f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
37917f01968SSiddharth Bhat   GPURuntime Runtime;
38017f01968SSiddharth Bhat 
38117f01968SSiddharth Bhat   /// The GPU Architecture to target.
38217f01968SSiddharth Bhat   GPUArch Arch;
38317f01968SSiddharth Bhat 
384472f9654STobias Grosser   /// Class to free isl_ids.
385472f9654STobias Grosser   class IslIdDeleter {
386472f9654STobias Grosser   public:
387472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
388472f9654STobias Grosser   };
389472f9654STobias Grosser 
390472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
391472f9654STobias Grosser   ///
392472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
393472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
394472f9654STobias Grosser 
395edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
396edb885cbSTobias Grosser 
39738fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
39838fc0aedSTobias Grosser   ///
39938fc0aedSTobias Grosser   /// These AST nodes can be of type:
40038fc0aedSTobias Grosser   ///
40138fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
40238fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
40313c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4045260c041STobias Grosser   ///   - In-kernel synchronization
4055260c041STobias Grosser   ///   - In-kernel memory copy statement
40638fc0aedSTobias Grosser   ///
4071fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4081fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
40932837fe3STobias Grosser 
41013c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
41113c78e4dSTobias Grosser 
41213c78e4dSTobias Grosser   /// Create code for a data transfer statement
41313c78e4dSTobias Grosser   ///
41413c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
41513c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
41613c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
41713c78e4dSTobias Grosser                           enum DataDirection Direction);
41813c78e4dSTobias Grosser 
419edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
420edb885cbSTobias Grosser   ///
421edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
422edb885cbSTobias Grosser   ///
423e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
424e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
425e53c924bSSiddharth Bhat   ///            kernel
426e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
427e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
428e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
429e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
430e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
431e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
432e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
433e53c924bSSiddharth Bhat   ///            Scops]
434e53c924bSSiddharth Bhat   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>>
435f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
436edb885cbSTobias Grosser 
43779a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
43879a947c2STobias Grosser   ///
43979a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
44079a947c2STobias Grosser   ///
44179a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
44279a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
44379a947c2STobias Grosser 
444abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
445abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
446abed4969SSiddharth Bhat   /// host pointers to the device.
447abed4969SSiddharth Bhat   /// \note
448abed4969SSiddharth Bhat   /// This is to be used only with managed memory
449abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
450abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
451abed4969SSiddharth Bhat 
45279a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
45379a947c2STobias Grosser   ///
45479a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
45579a947c2STobias Grosser   ///
45679a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
45779a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
45879a947c2STobias Grosser 
459a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
460a90be207SSiddharth Bhat   /// parameters.
461a90be207SSiddharth Bhat   ///
462a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
463a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
464a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
465a90be207SSiddharth Bhat   ///                   parameter.
466a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
467a90be207SSiddharth Bhat                             int Index);
468a90be207SSiddharth Bhat 
46979a947c2STobias Grosser   /// Create kernel launch parameters.
47079a947c2STobias Grosser   ///
47179a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
47279a947c2STobias Grosser   /// @param F             The kernel function that has been created.
47357693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
47479a947c2STobias Grosser   ///
47579a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
47679a947c2STobias Grosser   ///          values that are passed to the kernel.
47757693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
47857693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
47979a947c2STobias Grosser 
480b513b491STobias Grosser   /// Create declarations for kernel variable.
481b513b491STobias Grosser   ///
482b513b491STobias Grosser   /// This includes shared memory declarations.
483b513b491STobias Grosser   ///
484b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
485b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
486b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
487b513b491STobias Grosser 
488c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
489c1c6a2a6STobias Grosser   ///
490c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
491c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
492c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
493c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
494c1c6a2a6STobias Grosser   /// as specified here.
495c1c6a2a6STobias Grosser   ///
496c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
497c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
498c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
499c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
500c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
501c1c6a2a6STobias Grosser                           Value *BlockDimZ);
502c1c6a2a6STobias Grosser 
50332837fe3STobias Grosser   /// Create GPU kernel.
50432837fe3STobias Grosser   ///
50532837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
50632837fe3STobias Grosser   ///
50732837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
50832837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
50932837fe3STobias Grosser 
51013c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
51113c78e4dSTobias Grosser   ///
51213c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
51313c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
51413c78e4dSTobias Grosser 
515aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
516aaabbbf8STobias Grosser   ///
517aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
518aaabbbf8STobias Grosser   ///
519aaabbbf8STobias Grosser   /// Example:
520aaabbbf8STobias Grosser   ///
521aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
522aaabbbf8STobias Grosser   ///     A[i + 42] += ...
523aaabbbf8STobias Grosser   ///
524aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
525aaabbbf8STobias Grosser   ///
526aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
527aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
528aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
529aaabbbf8STobias Grosser 
53000bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
53100bb5a99STobias Grosser   ///
53200bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
53300bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
53400bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
53500bb5a99STobias Grosser 
53632837fe3STobias Grosser   /// Create kernel function.
53732837fe3STobias Grosser   ///
53832837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
53932837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
54032837fe3STobias Grosser   /// start block of this newly created function.
54132837fe3STobias Grosser   ///
54232837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
543edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
544f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
545f291c8d5SSiddharth Bhat   ///                         kernel.
546edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
547f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
548f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
54932837fe3STobias Grosser 
55032837fe3STobias Grosser   /// Create the declaration of a kernel function.
55132837fe3STobias Grosser   ///
55232837fe3STobias Grosser   /// The kernel function takes as arguments:
55332837fe3STobias Grosser   ///
55432837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
555f6044bd0STobias Grosser   ///   - Host iterators
556c84a1995STobias Grosser   ///   - Parameters
55732837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
55832837fe3STobias Grosser   ///
55932837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
560edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
561edb885cbSTobias Grosser   ///
56232837fe3STobias Grosser   /// @returns The newly declared function.
563edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
564edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
56532837fe3STobias Grosser 
566472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
567472f9654STobias Grosser   ///
568472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
569472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
570472f9654STobias Grosser 
5712f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5722f3073b5SPhilipp Schaad   ///
5732f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5742f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5752f3073b5SPhilipp Schaad 
576f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
577f291c8d5SSiddharth Bhat   ///
578f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
579f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
580f291c8d5SSiddharth Bhat   ///
581f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
582f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
583f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
584f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
585f291c8d5SSiddharth Bhat   ///
586f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
587f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
588f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
589f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
590f291c8d5SSiddharth Bhat   ///
591f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
592f291c8d5SSiddharth Bhat   ///                         this kernel.
593f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
594f291c8d5SSiddharth Bhat 
595b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
596b513b491STobias Grosser   ///
597b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
598b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
599b513b491STobias Grosser 
600edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
601edb885cbSTobias Grosser   ///
602edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
603edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
604edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
605edb885cbSTobias Grosser 
6065260c041STobias Grosser   /// Create an in-kernel synchronization call.
6075260c041STobias Grosser   void createKernelSync();
6085260c041STobias Grosser 
60974dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
61074dc3cb4STobias Grosser   ///
61174dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
61274dc3cb4STobias Grosser   std::string createKernelASM();
61374dc3cb4STobias Grosser 
61474dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
61574dc3cb4STobias Grosser   ///
61674dc3cb4STobias Grosser   /// @param F The function to remove references to.
61774dc3cb4STobias Grosser   void clearDominators(Function *F);
61874dc3cb4STobias Grosser 
61974dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
62074dc3cb4STobias Grosser   ///
62174dc3cb4STobias Grosser   /// @param F The function to remove references to.
62274dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
62374dc3cb4STobias Grosser 
62474dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
62574dc3cb4STobias Grosser   ///
62674dc3cb4STobias Grosser   /// @param F The function to remove references to.
62774dc3cb4STobias Grosser   void clearLoops(Function *F);
62874dc3cb4STobias Grosser 
6298fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6308fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6318fc6cdfbSTobias Grosser 
6328fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6338fc6cdfbSTobias Grosser   void addCUDALibDevice();
6348fc6cdfbSTobias Grosser 
63532837fe3STobias Grosser   /// Finalize the generation of the kernel function.
63632837fe3STobias Grosser   ///
63732837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
63832837fe3STobias Grosser   /// dump its IR to stderr.
63957793596STobias Grosser   ///
64057793596STobias Grosser   /// @returns The Assembly string of the kernel.
64157793596STobias Grosser   std::string finalizeKernelFunction();
642fa7b0802STobias Grosser 
64351dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
64451dfc275STobias Grosser   ///
64551dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
646a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
64751dfc275STobias Grosser   /// the kernel terminates.
64851dfc275STobias Grosser   ///
64951dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
65051dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
65151dfc275STobias Grosser 
6527287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
653fa7b0802STobias Grosser   void allocateDeviceArrays();
654fa7b0802STobias Grosser 
6557287aeddSTobias Grosser   /// Free all allocated device arrays.
6567287aeddSTobias Grosser   void freeDeviceArrays();
6577287aeddSTobias Grosser 
658fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
659fa7b0802STobias Grosser   ///
660fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
661fa7b0802STobias Grosser   Value *createCallInitContext();
662fa7b0802STobias Grosser 
66379a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
66479a947c2STobias Grosser   ///
66579a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
66679a947c2STobias Grosser   ///
66779a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
66879a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
66979a947c2STobias Grosser 
670fa7b0802STobias Grosser   /// Create a call to free the GPU context.
671fa7b0802STobias Grosser   ///
672fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
673fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
674fa7b0802STobias Grosser 
6757287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6767287aeddSTobias Grosser   ///
6777287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6787287aeddSTobias Grosser   ///
6797287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
680fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6817287aeddSTobias Grosser 
6827287aeddSTobias Grosser   /// Create a call to free a device array.
6837287aeddSTobias Grosser   ///
6847287aeddSTobias Grosser   /// @param Array The device array to free.
6857287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
68613c78e4dSTobias Grosser 
68713c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
68813c78e4dSTobias Grosser   ///
68913c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
69013c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
69113c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
69213c78e4dSTobias Grosser                                       Value *Size);
69313c78e4dSTobias Grosser 
69413c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
69513c78e4dSTobias Grosser   ///
69613c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
69713c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
69813c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
69913c78e4dSTobias Grosser                                       Value *Size);
70057793596STobias Grosser 
701abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
702abed4969SSiddharth Bhat   /// \note
703abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
704abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
705abed4969SSiddharth Bhat 
70657793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
70757793596STobias Grosser   ///
70857793596STobias Grosser   /// @param Buffer The string describing the kernel.
70957793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
71057793596STobias Grosser   ///
71157793596STobias Grosser   /// @returns A pointer to a kernel object
71257793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
71357793596STobias Grosser 
71457793596STobias Grosser   /// Create a call to free a GPU kernel.
71557793596STobias Grosser   ///
71657793596STobias Grosser   /// @param GPUKernel THe kernel to free.
71757793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
71879a947c2STobias Grosser 
71979a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
72079a947c2STobias Grosser   ///
72179a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
72279a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
72379a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
72479a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
72579a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
72679a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
727a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
72879a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
72979a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
73079a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
73179a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
73279a947c2STobias Grosser                               Value *Parameters);
7331fb9b64dSTobias Grosser };
7341fb9b64dSTobias Grosser 
73579f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7361abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7371abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
73879f13b9aSSingapuram Sanjay Srivallabh }
73979f13b9aSSingapuram Sanjay Srivallabh 
740fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
741750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
742750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
743750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
744750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
745750160e2STobias Grosser 
746fa7b0802STobias Grosser   GPUContext = createCallInitContext();
747abed4969SSiddharth Bhat 
748abed4969SSiddharth Bhat   if (!ManagedMemory)
749fa7b0802STobias Grosser     allocateDeviceArrays();
750fa7b0802STobias Grosser }
751fa7b0802STobias Grosser 
752fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
753abed4969SSiddharth Bhat   if (!ManagedMemory)
7547287aeddSTobias Grosser     freeDeviceArrays();
755abed4969SSiddharth Bhat 
756fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
757fa7b0802STobias Grosser   IslNodeBuilder::finalize();
758fa7b0802STobias Grosser }
759fa7b0802STobias Grosser 
760fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
761abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
762abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
763fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
764fa7b0802STobias Grosser 
765fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
766fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
76713c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7687287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7697287aeddSTobias Grosser     DevArrayName.append(Array->name);
770fa7b0802STobias Grosser 
77113c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
772aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
773aaabbbf8STobias Grosser     if (Offset)
774aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
775aaabbbf8STobias Grosser           ArraySize,
776aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
777aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7787287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7797287aeddSTobias Grosser     DevArray->setName(DevArrayName);
78013c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
781fa7b0802STobias Grosser   }
782fa7b0802STobias Grosser 
783fa7b0802STobias Grosser   isl_ast_build_free(Build);
784fa7b0802STobias Grosser }
785fa7b0802STobias Grosser 
786c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
787c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
788c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
789c1c6a2a6STobias Grosser 
790c1c6a2a6STobias Grosser   for (auto &F : *M) {
791c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
792c1c6a2a6STobias Grosser       continue;
793c1c6a2a6STobias Grosser 
794c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
795c1c6a2a6STobias Grosser 
796c1c6a2a6STobias Grosser     Metadata *Elements[] = {
797c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
798c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
799c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
800c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
801c1c6a2a6STobias Grosser     };
802c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
803c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
804c1c6a2a6STobias Grosser   }
805c1c6a2a6STobias Grosser }
806c1c6a2a6STobias Grosser 
8077287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
808abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
80913c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
81013c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8117287aeddSTobias Grosser }
8127287aeddSTobias Grosser 
81357793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
81457793596STobias Grosser   const char *Name = "polly_getKernel";
81557793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
81657793596STobias Grosser   Function *F = M->getFunction(Name);
81757793596STobias Grosser 
81857793596STobias Grosser   // If F is not available, declare it.
81957793596STobias Grosser   if (!F) {
82057793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
82157793596STobias Grosser     std::vector<Type *> Args;
82257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
82557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
82657793596STobias Grosser   }
82757793596STobias Grosser 
82857793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
82957793596STobias Grosser }
83057793596STobias Grosser 
83179a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
83279a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
83379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
83479a947c2STobias Grosser   Function *F = M->getFunction(Name);
83579a947c2STobias Grosser 
83679a947c2STobias Grosser   // If F is not available, declare it.
83779a947c2STobias Grosser   if (!F) {
83879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
83979a947c2STobias Grosser     std::vector<Type *> Args;
84079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
84179a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
84279a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
84379a947c2STobias Grosser   }
84479a947c2STobias Grosser 
84579a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
84679a947c2STobias Grosser }
84779a947c2STobias Grosser 
84879a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
84979a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
85079a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
85179a947c2STobias Grosser                                             Value *Parameters) {
85279a947c2STobias Grosser   const char *Name = "polly_launchKernel";
85379a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
85479a947c2STobias Grosser   Function *F = M->getFunction(Name);
85579a947c2STobias Grosser 
85679a947c2STobias Grosser   // If F is not available, declare it.
85779a947c2STobias Grosser   if (!F) {
85879a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
85979a947c2STobias Grosser     std::vector<Type *> Args;
86079a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
86179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
86279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
86379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
86479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
86579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
86679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
86779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
86879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
86979a947c2STobias Grosser   }
87079a947c2STobias Grosser 
871ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
87279a947c2STobias Grosser                          BlockDimZ, Parameters});
87379a947c2STobias Grosser }
87479a947c2STobias Grosser 
87557793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
87657793596STobias Grosser   const char *Name = "polly_freeKernel";
87757793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
87857793596STobias Grosser   Function *F = M->getFunction(Name);
87957793596STobias Grosser 
88057793596STobias Grosser   // If F is not available, declare it.
88157793596STobias Grosser   if (!F) {
88257793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
88357793596STobias Grosser     std::vector<Type *> Args;
88457793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
88557793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
88657793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
88757793596STobias Grosser   }
88857793596STobias Grosser 
88957793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
89057793596STobias Grosser }
89157793596STobias Grosser 
8927287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
893abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
894abed4969SSiddharth Bhat                            "for device");
8957287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8967287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8977287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8987287aeddSTobias Grosser 
8997287aeddSTobias Grosser   // If F is not available, declare it.
9007287aeddSTobias Grosser   if (!F) {
9017287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9027287aeddSTobias Grosser     std::vector<Type *> Args;
9037287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9047287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9057287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9067287aeddSTobias Grosser   }
9077287aeddSTobias Grosser 
9087287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9097287aeddSTobias Grosser }
9107287aeddSTobias Grosser 
911fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
912abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
913abed4969SSiddharth Bhat                            "for device");
914fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
915fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
916fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
917fa7b0802STobias Grosser 
918fa7b0802STobias Grosser   // If F is not available, declare it.
919fa7b0802STobias Grosser   if (!F) {
920fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
921fa7b0802STobias Grosser     std::vector<Type *> Args;
922fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
923fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
924fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
925fa7b0802STobias Grosser   }
926fa7b0802STobias Grosser 
927fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
928fa7b0802STobias Grosser }
929fa7b0802STobias Grosser 
93013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
93113c78e4dSTobias Grosser                                                     Value *DeviceData,
93213c78e4dSTobias Grosser                                                     Value *Size) {
933abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
934abed4969SSiddharth Bhat                            "device and host");
93513c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
93613c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
93713c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
93813c78e4dSTobias Grosser 
93913c78e4dSTobias Grosser   // If F is not available, declare it.
94013c78e4dSTobias Grosser   if (!F) {
94113c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
94213c78e4dSTobias Grosser     std::vector<Type *> Args;
94313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
94413c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
94513c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
94613c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
94713c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
94813c78e4dSTobias Grosser   }
94913c78e4dSTobias Grosser 
95013c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
95113c78e4dSTobias Grosser }
95213c78e4dSTobias Grosser 
95313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
95413c78e4dSTobias Grosser                                                     Value *HostData,
95513c78e4dSTobias Grosser                                                     Value *Size) {
956abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
957abed4969SSiddharth Bhat                            "device and host");
95813c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
95913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
96013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
96113c78e4dSTobias Grosser 
96213c78e4dSTobias Grosser   // If F is not available, declare it.
96313c78e4dSTobias Grosser   if (!F) {
96413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
96513c78e4dSTobias Grosser     std::vector<Type *> Args;
96613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
96713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
96813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
96913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
97013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
97113c78e4dSTobias Grosser   }
97213c78e4dSTobias Grosser 
97313c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
97413c78e4dSTobias Grosser }
97513c78e4dSTobias Grosser 
976abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
977abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
978abed4969SSiddharth Bhat                           "managed memory");
979abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
980abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
981abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
982abed4969SSiddharth Bhat 
983abed4969SSiddharth Bhat   // If F is not available, declare it.
984abed4969SSiddharth Bhat   if (!F) {
985abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
986abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
987abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
988abed4969SSiddharth Bhat   }
989abed4969SSiddharth Bhat 
990abed4969SSiddharth Bhat   Builder.CreateCall(F);
991abed4969SSiddharth Bhat }
992abed4969SSiddharth Bhat 
993fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
99417f01968SSiddharth Bhat   const char *Name;
99517f01968SSiddharth Bhat 
99617f01968SSiddharth Bhat   switch (Runtime) {
99717f01968SSiddharth Bhat   case GPURuntime::CUDA:
99817f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
99917f01968SSiddharth Bhat     break;
100017f01968SSiddharth Bhat   case GPURuntime::OpenCL:
100117f01968SSiddharth Bhat     Name = "polly_initContextCL";
100217f01968SSiddharth Bhat     break;
100317f01968SSiddharth Bhat   }
100417f01968SSiddharth Bhat 
1005fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1006fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1007fa7b0802STobias Grosser 
1008fa7b0802STobias Grosser   // If F is not available, declare it.
1009fa7b0802STobias Grosser   if (!F) {
1010fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1011fa7b0802STobias Grosser     std::vector<Type *> Args;
1012fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1013fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1014fa7b0802STobias Grosser   }
1015fa7b0802STobias Grosser 
1016fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1017fa7b0802STobias Grosser }
1018fa7b0802STobias Grosser 
1019fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1020fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1021fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1022fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1023fa7b0802STobias Grosser 
1024fa7b0802STobias Grosser   // If F is not available, declare it.
1025fa7b0802STobias Grosser   if (!F) {
1026fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1027fa7b0802STobias Grosser     std::vector<Type *> Args;
1028fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1029fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1030fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1031fa7b0802STobias Grosser   }
1032fa7b0802STobias Grosser 
1033fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1034fa7b0802STobias Grosser }
1035fa7b0802STobias Grosser 
10365260c041STobias Grosser /// Check if one string is a prefix of another.
10375260c041STobias Grosser ///
10385260c041STobias Grosser /// @param String The string in which to look for the prefix.
10395260c041STobias Grosser /// @param Prefix The prefix to look for.
10405260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10415260c041STobias Grosser   return String.find(Prefix) == 0;
10425260c041STobias Grosser }
10435260c041STobias Grosser 
104413c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1045f7face4bSSiddharth Bhat   isl::ast_build Build =
1046f7face4bSSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
104713c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
104813c78e4dSTobias Grosser 
104913c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1050f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1051f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1052f7face4bSSiddharth Bhat 
1053f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1054f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
105513c78e4dSTobias Grosser 
105613c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1057f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1058f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1059f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
106013c78e4dSTobias Grosser     }
106113c78e4dSTobias Grosser 
1062f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1063b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1064b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
106513c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
106613c78e4dSTobias Grosser   }
106713c78e4dSTobias Grosser   return ArraySize;
106813c78e4dSTobias Grosser }
106913c78e4dSTobias Grosser 
1070aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1071aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1072aaabbbf8STobias Grosser     return nullptr;
1073aaabbbf8STobias Grosser 
1074ccbf4b50SSiddharth Bhat   isl::ast_build Build =
1075ccbf4b50SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
1076aaabbbf8STobias Grosser 
1077ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1078aaabbbf8STobias Grosser 
1079ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1080aaabbbf8STobias Grosser 
1081ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1082ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1083aaabbbf8STobias Grosser 
1084ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1085aaabbbf8STobias Grosser     return nullptr;
1086aaabbbf8STobias Grosser   }
1087aaabbbf8STobias Grosser 
1088ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1089aaabbbf8STobias Grosser 
1090ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1091aaabbbf8STobias Grosser     if (i > 0) {
1092ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1093ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1094ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1095ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1096aaabbbf8STobias Grosser     }
1097ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1098ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1099ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1100aaabbbf8STobias Grosser   }
1101aaabbbf8STobias Grosser 
1102ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1103aaabbbf8STobias Grosser }
1104aaabbbf8STobias Grosser 
1105abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1106abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1107abed4969SSiddharth Bhat 
1108abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1109abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1110abed4969SSiddharth Bhat                           "with managed memory");
1111abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1112abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1113abed4969SSiddharth Bhat     return it->second;
1114abed4969SSiddharth Bhat   } else {
1115abed4969SSiddharth Bhat     Value *HostPtr;
1116abed4969SSiddharth Bhat 
1117abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1118abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1119abed4969SSiddharth Bhat     else
1120abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1121edf9581eSSiddharth Bhat     HostPtr = getLatestValue(HostPtr);
1122abed4969SSiddharth Bhat 
1123abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1124abed4969SSiddharth Bhat     if (Offset) {
1125abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1126abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1127abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1128abed4969SSiddharth Bhat     }
1129abed4969SSiddharth Bhat 
1130abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1131abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1132abed4969SSiddharth Bhat     return HostPtr;
1133abed4969SSiddharth Bhat   }
1134abed4969SSiddharth Bhat }
1135abed4969SSiddharth Bhat 
113613c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
113713c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1138abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
113913c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
114013c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
114113c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
114213c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
114313c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
114413c78e4dSTobias Grosser 
114513c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1146aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
114713c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
114813c78e4dSTobias Grosser 
1149b06ff457STobias Grosser   Value *HostPtr;
1150b06ff457STobias Grosser 
1151b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1152b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1153b06ff457STobias Grosser   else
1154b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1155edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
115613c78e4dSTobias Grosser 
1157aaabbbf8STobias Grosser   if (Offset) {
1158aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1159aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1160aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1161aaabbbf8STobias Grosser   }
1162aaabbbf8STobias Grosser 
116313c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
116413c78e4dSTobias Grosser 
1165aaabbbf8STobias Grosser   if (Offset) {
1166aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1167ff40087aSTobias Grosser         Size, Builder.CreateMul(
1168ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1169aaabbbf8STobias Grosser   }
1170aaabbbf8STobias Grosser 
117113c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
117213c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
117313c78e4dSTobias Grosser   else
117413c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
117513c78e4dSTobias Grosser 
117613c78e4dSTobias Grosser   isl_id_free(Id);
117713c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
117813c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
117913c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
118013c78e4dSTobias Grosser }
118113c78e4dSTobias Grosser 
11821fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
118332837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
118432837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
118532837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
118632837fe3STobias Grosser   isl_id_free(Id);
118732837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
118832837fe3STobias Grosser 
118932837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
119032837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
119132837fe3STobias Grosser     createKernel(UserStmt);
119232837fe3STobias Grosser     isl_ast_expr_free(Expr);
119332837fe3STobias Grosser     return;
119432837fe3STobias Grosser   }
11959e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11969e3db2b7SSiddharth Bhat     initializeAfterRTH();
11979e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11989e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11999e3db2b7SSiddharth Bhat     return;
12009e3db2b7SSiddharth Bhat   }
12019e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12029e3db2b7SSiddharth Bhat     finalize();
12039e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12049e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12059e3db2b7SSiddharth Bhat     return;
12069e3db2b7SSiddharth Bhat   }
120713c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1208abed4969SSiddharth Bhat     if (!ManagedMemory)
120913c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1210abed4969SSiddharth Bhat     else
1211abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1212abed4969SSiddharth Bhat 
121332837fe3STobias Grosser     isl_ast_expr_free(Expr);
121413c78e4dSTobias Grosser     return;
121513c78e4dSTobias Grosser   }
121613c78e4dSTobias Grosser 
121713c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1218abed4969SSiddharth Bhat     if (!ManagedMemory) {
121913c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1220abed4969SSiddharth Bhat     } else {
1221abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1222abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1223abed4969SSiddharth Bhat     }
122413c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
122538fc0aedSTobias Grosser     return;
122638fc0aedSTobias Grosser   }
122738fc0aedSTobias Grosser 
12285260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12295260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12305260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12315260c041STobias Grosser   isl_id_free(Anno);
12325260c041STobias Grosser 
12335260c041STobias Grosser   switch (KernelStmt->type) {
12345260c041STobias Grosser   case ppcg_kernel_domain:
1235edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12365260c041STobias Grosser     isl_ast_node_free(UserStmt);
12375260c041STobias Grosser     return;
12385260c041STobias Grosser   case ppcg_kernel_copy:
1239b513b491STobias Grosser     createKernelCopy(KernelStmt);
12405260c041STobias Grosser     isl_ast_expr_free(Expr);
12415260c041STobias Grosser     isl_ast_node_free(UserStmt);
12425260c041STobias Grosser     return;
12435260c041STobias Grosser   case ppcg_kernel_sync:
12445260c041STobias Grosser     createKernelSync();
12455260c041STobias Grosser     isl_ast_expr_free(Expr);
12465260c041STobias Grosser     isl_ast_node_free(UserStmt);
12475260c041STobias Grosser     return;
12485260c041STobias Grosser   }
12495260c041STobias Grosser 
12505260c041STobias Grosser   isl_ast_expr_free(Expr);
12515260c041STobias Grosser   isl_ast_node_free(UserStmt);
12525260c041STobias Grosser   return;
12535260c041STobias Grosser }
1254b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1255b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1256b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1257b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1258b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1259b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1260b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1261b513b491STobias Grosser 
1262b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1263b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1264b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1265b513b491STobias Grosser   } else {
1266b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1267b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1268b513b491STobias Grosser   }
1269b513b491STobias Grosser }
12705260c041STobias Grosser 
1271edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1272edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1273edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1274edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1275edb885cbSTobias Grosser 
1276edb885cbSTobias Grosser   LoopToScevMapT LTS;
1277edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1278edb885cbSTobias Grosser 
1279edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1280edb885cbSTobias Grosser 
1281edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1282edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1283edb885cbSTobias Grosser   else
1284a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1285edb885cbSTobias Grosser }
1286edb885cbSTobias Grosser 
12875260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12885260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12892f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
129017f01968SSiddharth Bhat 
129117f01968SSiddharth Bhat   Function *Sync;
129217f01968SSiddharth Bhat 
129317f01968SSiddharth Bhat   switch (Arch) {
12942f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12952f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12962f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12972f3073b5SPhilipp Schaad 
12982f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12992f3073b5SPhilipp Schaad     if (!Sync) {
13002f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13012f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13022f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13032f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13042f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13052f3073b5SPhilipp Schaad     }
13062f3073b5SPhilipp Schaad     break;
130717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
130817f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
130917f01968SSiddharth Bhat     break;
131017f01968SSiddharth Bhat   }
131117f01968SSiddharth Bhat 
13125260c041STobias Grosser   Builder.CreateCall(Sync, {});
13135260c041STobias Grosser }
13145260c041STobias Grosser 
1315edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1316edb885cbSTobias Grosser ///
1317edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1318edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1319edb885cbSTobias Grosser ///
1320edb885cbSTobias Grosser /// @param Node The node to collect references for.
1321edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1322edb885cbSTobias Grosser ///
1323edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1324edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1325edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1326edb885cbSTobias Grosser     return isl_bool_true;
1327edb885cbSTobias Grosser 
1328edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1329edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1330edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1331edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1332edb885cbSTobias Grosser   isl_id_free(Id);
1333edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1334edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1335edb885cbSTobias Grosser 
1336edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1337edb885cbSTobias Grosser     return isl_bool_true;
1338edb885cbSTobias Grosser 
1339edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1340edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1341edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1342edb885cbSTobias Grosser   isl_id_free(Id);
1343edb885cbSTobias Grosser 
134400bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1345edb885cbSTobias Grosser 
1346edb885cbSTobias Grosser   return isl_bool_true;
1347edb885cbSTobias Grosser }
1348edb885cbSTobias Grosser 
13498fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13508fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13518fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13528fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13538fc6cdfbSTobias Grosser 
13548fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13558fc6cdfbSTobias Grosser ///
13568fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13578fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13588fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13598fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13608fc6cdfbSTobias Grosser 
13618fc6cdfbSTobias Grosser   return "";
13628fc6cdfbSTobias Grosser }
13638fc6cdfbSTobias Grosser 
1364f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13658fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1366f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1367f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
136854491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
136954491db6STobias Grosser   // "llvm.copysign".
137054491db6STobias Grosser   const StringRef Name = F->getName();
13718fc6cdfbSTobias Grosser 
13728fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13738fc6cdfbSTobias Grosser     return true;
13748fc6cdfbSTobias Grosser 
137554491db6STobias Grosser   return F->isIntrinsic() &&
137654491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
137754491db6STobias Grosser           Name.startswith("llvm.copysign"));
1378f291c8d5SSiddharth Bhat }
1379f291c8d5SSiddharth Bhat 
1380f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1381f291c8d5SSiddharth Bhat ///
1382f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1383f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1384f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1385f291c8d5SSiddharth Bhat /// `Function`s.
1386f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1387f291c8d5SSiddharth Bhat 
1388f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1389f291c8d5SSiddharth Bhat static SetVector<Function *>
13908fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13918fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1392f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1393f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1394f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1395f291c8d5SSiddharth Bhat     if (F) {
13968fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
13978fc6cdfbSTobias Grosser              "Code should have bailed out by "
1398f291c8d5SSiddharth Bhat              "this point if an invalid function "
1399f291c8d5SSiddharth Bhat              "were present in a kernel.");
1400f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1401f291c8d5SSiddharth Bhat     }
1402f291c8d5SSiddharth Bhat   }
1403f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1404f291c8d5SSiddharth Bhat }
1405f291c8d5SSiddharth Bhat 
1406e53c924bSSiddharth Bhat std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>>
1407f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1408edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1409edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1410edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1411edb885cbSTobias Grosser   SubtreeReferences References = {
1412edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1413edb885cbSTobias Grosser 
1414edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1415edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1416edb885cbSTobias Grosser 
1417e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1418e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1419e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1420e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1421e53c924bSSiddharth Bhat 
1422edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1423edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1424edb885cbSTobias Grosser 
1425e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1426edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1427e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1428e53c924bSSiddharth Bhat   }
1429e53c924bSSiddharth Bhat 
1430e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1431e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1432e53c924bSSiddharth Bhat   });
1433edb885cbSTobias Grosser 
1434edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1435d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1436edb885cbSTobias Grosser 
1437edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1438edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1439edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1440edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1441edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1442edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1443edb885cbSTobias Grosser     isl_id_free(Id);
1444edb885cbSTobias Grosser   }
1445edb885cbSTobias Grosser   isl_space_free(Space);
1446edb885cbSTobias Grosser 
1447edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1448edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1449edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1450edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1451edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1452edb885cbSTobias Grosser     isl_id_free(Id);
1453edb885cbSTobias Grosser   }
1454edb885cbSTobias Grosser 
1455f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1456f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1457f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1458f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1459f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1460f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1461f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1462f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1463f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14648fc6cdfbSTobias Grosser 
14658fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14668fc6cdfbSTobias Grosser 
1467f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14688fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1469f291c8d5SSiddharth Bhat 
1470a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1471a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1472a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1473a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1474a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1475a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1476a1b2086aSSiddharth Bhat     else
1477a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1478a1b2086aSSiddharth Bhat   }
1479e53c924bSSiddharth Bhat   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops);
1480edb885cbSTobias Grosser }
1481edb885cbSTobias Grosser 
148274dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
148374dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
148474dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
148574dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
148674dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
148774dc3cb4STobias Grosser 
148874dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
148974dc3cb4STobias Grosser     DT.eraseNode(BB);
149074dc3cb4STobias Grosser }
149174dc3cb4STobias Grosser 
149274dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
149374dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
149474dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
149574dc3cb4STobias Grosser     if (L)
149674dc3cb4STobias Grosser       SE.forgetLoop(L);
149774dc3cb4STobias Grosser   }
149874dc3cb4STobias Grosser }
149974dc3cb4STobias Grosser 
150074dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
150174dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
150274dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
150374dc3cb4STobias Grosser     if (L)
150474dc3cb4STobias Grosser       SE.forgetLoop(L);
150574dc3cb4STobias Grosser     LI.removeBlock(&BB);
150674dc3cb4STobias Grosser   }
150774dc3cb4STobias Grosser }
150874dc3cb4STobias Grosser 
150979a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
151079a947c2STobias Grosser   std::vector<Value *> Sizes;
15114d5820d1SSiddharth Bhat   isl::ast_build Context =
15124d5820d1SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
151379a947c2STobias Grosser 
15144d5820d1SSiddharth Bhat   isl::multi_pw_aff GridSizePwAffs =
15154d5820d1SSiddharth Bhat       isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size));
151679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
15174d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
15184d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15194d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
152079a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
152179a947c2STobias Grosser     Sizes.push_back(Res);
152279a947c2STobias Grosser   }
152379a947c2STobias Grosser 
152479a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
152579a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
152679a947c2STobias Grosser 
152779a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
152879a947c2STobias Grosser }
152979a947c2STobias Grosser 
153079a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
153179a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
153279a947c2STobias Grosser   std::vector<Value *> Sizes;
153379a947c2STobias Grosser 
153479a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
153579a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
153679a947c2STobias Grosser     Sizes.push_back(Res);
153779a947c2STobias Grosser   }
153879a947c2STobias Grosser 
153979a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
154079a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
154179a947c2STobias Grosser 
154279a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
154379a947c2STobias Grosser }
154479a947c2STobias Grosser 
1545a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1546a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1547a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1548a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1549a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1550a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1551a90be207SSiddharth Bhat }
1552a90be207SSiddharth Bhat 
155357693272STobias Grosser Value *
155457693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
155557693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1556a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1557a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1558a90be207SSiddharth Bhat 
1559a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
156079a947c2STobias Grosser 
156179a947c2STobias Grosser   BasicBlock *EntryBlock =
156279a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
156367726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
156479a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
156567726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
156667726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
156779a947c2STobias Grosser 
156879a947c2STobias Grosser   int Index = 0;
156979a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
157079a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
157179a947c2STobias Grosser       continue;
157279a947c2STobias Grosser 
157379a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1574206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
157579a947c2STobias Grosser 
1576a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1577a90be207SSiddharth Bhat 
1578abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1579abed4969SSiddharth Bhat     if (ManagedMemory) {
1580abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1581abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1582abed4969SSiddharth Bhat     } else {
1583abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
158479a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1585abed4969SSiddharth Bhat     }
1586abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1587abed4969SSiddharth Bhat                                   "initialized");
1588aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1589aaabbbf8STobias Grosser 
1590aaabbbf8STobias Grosser     if (Offset) {
1591aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1592aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1593aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1594aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1595aaabbbf8STobias Grosser     }
1596fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1597fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1598aaabbbf8STobias Grosser 
1599fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1600abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1601abed4969SSiddharth Bhat       if (ManagedMemory)
1602abed4969SSiddharth Bhat         ValPtr = DevArray;
1603abed4969SSiddharth Bhat       else
1604abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1605abed4969SSiddharth Bhat 
1606abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1607abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1608fe74a7a1STobias Grosser       Value *ValPtrCast =
1609fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1610fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1611fe74a7a1STobias Grosser     } else {
161267726b32STobias Grosser       Instruction *Param =
161367726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
161467726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
161579a947c2STobias Grosser                          EntryBlock->getTerminator());
161679a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
161779a947c2STobias Grosser       Value *ParamTyped =
161879a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
161979a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1620fe74a7a1STobias Grosser     }
162179a947c2STobias Grosser     Index++;
162279a947c2STobias Grosser   }
162379a947c2STobias Grosser 
1624a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1625a490147cSTobias Grosser 
1626a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1627a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1628a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1629a490147cSTobias Grosser     isl_id_free(Id);
1630a90be207SSiddharth Bhat 
1631a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1632a90be207SSiddharth Bhat 
163367726b32STobias Grosser     Instruction *Param =
163467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
163567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1636a490147cSTobias Grosser                        EntryBlock->getTerminator());
1637a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1638a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1639a490147cSTobias Grosser     Index++;
1640a490147cSTobias Grosser   }
1641a490147cSTobias Grosser 
1642d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1643d8b94bcaSTobias Grosser 
1644d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1645d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1646d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1647a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1648a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1649d8b94bcaSTobias Grosser     isl_id_free(Id);
1650a90be207SSiddharth Bhat 
1651a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1652a90be207SSiddharth Bhat 
165367726b32STobias Grosser     Instruction *Param =
165467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
165567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1656d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1657d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1658a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1659d8b94bcaSTobias Grosser     Index++;
1660d8b94bcaSTobias Grosser   }
1661d8b94bcaSTobias Grosser 
166257693272STobias Grosser   for (auto Val : SubtreeValues) {
1663a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1664a90be207SSiddharth Bhat 
166567726b32STobias Grosser     Instruction *Param =
166667726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
166767726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
166857693272STobias Grosser                        EntryBlock->getTerminator());
166957693272STobias Grosser     Builder.CreateStore(Val, Param);
1670a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1671a90be207SSiddharth Bhat     Index++;
1672a90be207SSiddharth Bhat   }
1673a90be207SSiddharth Bhat 
1674a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1675a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1676a90be207SSiddharth Bhat     Instruction *Param =
1677a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1678a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1679a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1680a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1681a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
168257693272STobias Grosser     Index++;
168357693272STobias Grosser   }
168457693272STobias Grosser 
168579a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
168679a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
168779a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
168879a947c2STobias Grosser }
168979a947c2STobias Grosser 
1690f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1691f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1692f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1693f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1694f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1695f291c8d5SSiddharth Bhat     if (!Clone)
1696f291c8d5SSiddharth Bhat       Clone =
1697f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1698f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1699f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1700f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1701f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1702f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1703f291c8d5SSiddharth Bhat   }
1704f291c8d5SSiddharth Bhat }
170532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
170632837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
170732837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
170832837fe3STobias Grosser   isl_id_free(Id);
170932837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
171032837fe3STobias Grosser 
1711bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1712bc653f20STobias Grosser     DeepestParallel =
1713bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1714bc653f20STobias Grosser   else
1715bc653f20STobias Grosser     DeepestSequential =
1716bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1717bc653f20STobias Grosser 
1718c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1719c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1720c1c6a2a6STobias Grosser 
1721f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1722f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1723e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
1724e53c924bSSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions, Loops) =
1725e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1726edb885cbSTobias Grosser 
172732837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
172832837fe3STobias Grosser 
172932837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1730472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1731edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1732587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1733b06ff457STobias Grosser   ScalarMap.clear();
173432837fe3STobias Grosser 
1735edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1736edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1737edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1738edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1739edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1740edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1741edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1742edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1743edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1744edb885cbSTobias Grosser     SubtreeValues.insert(V);
1745edb885cbSTobias Grosser   }
1746edb885cbSTobias Grosser 
1747f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1748f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
174932837fe3STobias Grosser 
175059ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
175159ab0705STobias Grosser 
175251dfc275STobias Grosser   finalizeKernelArguments(Kernel);
175374dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17542f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1755c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
175674dc3cb4STobias Grosser   clearDominators(F);
175774dc3cb4STobias Grosser   clearScalarEvolution(F);
175874dc3cb4STobias Grosser   clearLoops(F);
175974dc3cb4STobias Grosser 
1760472f9654STobias Grosser   IDToValue = HostIDs;
176132837fe3STobias Grosser 
1762b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1763b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1764edb885cbSTobias Grosser   EscapeMap.clear();
1765edb885cbSTobias Grosser   IDToSAI.clear();
176674dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
176774dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17684d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
176974dc3cb4STobias Grosser   LocalArrays.clear();
1770edb885cbSTobias Grosser 
177151dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
177251dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
177357693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
177479a947c2STobias Grosser 
177579f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
177657793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
177757793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
177857793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
177979a947c2STobias Grosser 
178079a947c2STobias Grosser   Value *GridDimX, *GridDimY;
178179a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
178279a947c2STobias Grosser 
178379a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
178479a947c2STobias Grosser                          BlockDimZ, Parameters);
178557793596STobias Grosser   createCallFreeKernel(GPUKernel);
1786b513b491STobias Grosser 
1787b513b491STobias Grosser   for (auto Id : KernelIds)
1788b513b491STobias Grosser     isl_id_free(Id);
1789b513b491STobias Grosser 
1790b513b491STobias Grosser   KernelIds.clear();
179132837fe3STobias Grosser }
179232837fe3STobias Grosser 
179332837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
179432837fe3STobias Grosser ///
179532837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
179632837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1797d277fedaSSiddharth Bhat   std::string Ret = "";
179832837fe3STobias Grosser 
1799d277fedaSSiddharth Bhat   if (!is64Bit) {
1800d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1802d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1803d277fedaSSiddharth Bhat   } else {
1804d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180530caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1806d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1807d277fedaSSiddharth Bhat   }
180832837fe3STobias Grosser 
180932837fe3STobias Grosser   return Ret;
181032837fe3STobias Grosser }
181132837fe3STobias Grosser 
18122f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
18132f3073b5SPhilipp Schaad ///
18142f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
18152f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
18162f3073b5SPhilipp Schaad   std::string Ret = "";
18172f3073b5SPhilipp Schaad 
18182f3073b5SPhilipp Schaad   if (!is64Bit) {
18192f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
182030caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18212f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18222f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18232f3073b5SPhilipp Schaad   } else {
18242f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
182530caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18262f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18272f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18282f3073b5SPhilipp Schaad   }
18292f3073b5SPhilipp Schaad 
18302f3073b5SPhilipp Schaad   return Ret;
18312f3073b5SPhilipp Schaad }
18322f3073b5SPhilipp Schaad 
1833edb885cbSTobias Grosser Function *
1834edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1835edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
183632837fe3STobias Grosser   std::vector<Type *> Args;
183779f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
183832837fe3STobias Grosser 
18392f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18402f3073b5SPhilipp Schaad 
184132837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
184232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
184332837fe3STobias Grosser       continue;
184432837fe3STobias Grosser 
1845fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1846fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1847206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1848fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18492f3073b5SPhilipp Schaad       MemoryType.push_back(
18502f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1851fe74a7a1STobias Grosser     } else {
1852d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1853d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18542f3073b5SPhilipp Schaad       MemoryType.push_back(
18552f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
185632837fe3STobias Grosser     }
1857fe74a7a1STobias Grosser   }
185832837fe3STobias Grosser 
1859f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1860f6044bd0STobias Grosser 
18612f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1862f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18632f3073b5SPhilipp Schaad     MemoryType.push_back(
18642f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18652f3073b5SPhilipp Schaad   }
1866f6044bd0STobias Grosser 
1867c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1868c84a1995STobias Grosser 
1869cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1870cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1871cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1872cf66ef26STobias Grosser     isl_id_free(Id);
1873cf66ef26STobias Grosser     Args.push_back(Val->getType());
18742f3073b5SPhilipp Schaad     MemoryType.push_back(
18752f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1876cf66ef26STobias Grosser   }
1877c84a1995STobias Grosser 
18782f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1879edb885cbSTobias Grosser     Args.push_back(V->getType());
18802f3073b5SPhilipp Schaad     MemoryType.push_back(
18812f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18822f3073b5SPhilipp Schaad   }
1883edb885cbSTobias Grosser 
188432837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
188532837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
188632837fe3STobias Grosser                               GPUModule.get());
188717f01968SSiddharth Bhat 
18882f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18892f3073b5SPhilipp Schaad 
18902f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18912f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18922f3073b5SPhilipp Schaad   }
18932f3073b5SPhilipp Schaad 
18942f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18952f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18962f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18972f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18982f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18992f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
19002f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19012f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
19022f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19032f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
19042f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19052f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
19062f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19072f3073b5SPhilipp Schaad   }
19082f3073b5SPhilipp Schaad 
190917f01968SSiddharth Bhat   switch (Arch) {
191017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
191132837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
191217f01968SSiddharth Bhat     break;
19132f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19142f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19152f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
19162f3073b5SPhilipp Schaad     break;
191717f01968SSiddharth Bhat   }
191832837fe3STobias Grosser 
191932837fe3STobias Grosser   auto Arg = FN->arg_begin();
192032837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
192132837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
192232837fe3STobias Grosser       continue;
192332837fe3STobias Grosser 
1924edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1925edb885cbSTobias Grosser 
1926edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1927206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1928206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1929edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1930edb885cbSTobias Grosser     Value *Val = &*Arg;
1931edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1932edb885cbSTobias Grosser     isl_ast_build *Build =
1933edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1934f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1935edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1936edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19379e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1938edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1939edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1940edb885cbSTobias Grosser     }
1941edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19424d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
194374dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1944edb885cbSTobias Grosser 
1945edb885cbSTobias Grosser     isl_ast_build_free(Build);
1946b513b491STobias Grosser     KernelIds.push_back(Id);
1947edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
194832837fe3STobias Grosser     Arg++;
194932837fe3STobias Grosser   }
195032837fe3STobias Grosser 
1951f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1952f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1953f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1954f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1955f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1956f6044bd0STobias Grosser     Arg++;
1957f6044bd0STobias Grosser   }
1958f6044bd0STobias Grosser 
1959c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1960c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1961c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
196212453403STobias Grosser     Value *Val = IDToValue[Id];
196312453403STobias Grosser     ValueMap[Val] = &*Arg;
1964c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1965c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1966c84a1995STobias Grosser     Arg++;
1967c84a1995STobias Grosser   }
1968c84a1995STobias Grosser 
1969edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1970edb885cbSTobias Grosser     Arg->setName(V->getName());
1971edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1972edb885cbSTobias Grosser     Arg++;
1973edb885cbSTobias Grosser   }
1974edb885cbSTobias Grosser 
197532837fe3STobias Grosser   return FN;
197632837fe3STobias Grosser }
197732837fe3STobias Grosser 
1978472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
197917f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
198017f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1981472f9654STobias Grosser 
198217f01968SSiddharth Bhat   switch (Arch) {
19832f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19842f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19852f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
198617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
198717f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
198817f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
198917f01968SSiddharth Bhat 
199017f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
199117f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
199217f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
199317f01968SSiddharth Bhat     break;
199417f01968SSiddharth Bhat   }
1995472f9654STobias Grosser 
1996472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1997472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1998472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1999472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2000472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2001472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2002472f9654STobias Grosser     IDToValue[Id] = Val;
2003472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2004472f9654STobias Grosser   };
2005472f9654STobias Grosser 
2006472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2007472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2008472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2009472f9654STobias Grosser   }
2010472f9654STobias Grosser 
2011472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2012472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2013472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2014472f9654STobias Grosser   }
2015472f9654STobias Grosser }
2016472f9654STobias Grosser 
20172f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
20182f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
20192f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
20202f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
20212f3073b5SPhilipp Schaad 
20222f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
20232f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
20242f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
20252f3073b5SPhilipp Schaad 
20262f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
20272f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20282f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20292f3073b5SPhilipp Schaad 
20302f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20312f3073b5SPhilipp Schaad     if (!FN) {
20322f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20332f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20342f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20352f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20362f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20372f3073b5SPhilipp Schaad     }
20382f3073b5SPhilipp Schaad 
20392f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20402f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20412f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20422f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20432f3073b5SPhilipp Schaad   };
20442f3073b5SPhilipp Schaad 
20452f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20462f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20472f3073b5SPhilipp Schaad 
20482f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20492f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20502f3073b5SPhilipp Schaad }
20512f3073b5SPhilipp Schaad 
205200bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
205300bb5a99STobias Grosser   auto Arg = FN->arg_begin();
205400bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
205500bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
205600bb5a99STobias Grosser       continue;
205700bb5a99STobias Grosser 
205800bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2059206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2060206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
206100bb5a99STobias Grosser     isl_id_free(Id);
206200bb5a99STobias Grosser 
206300bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
206400bb5a99STobias Grosser       Arg++;
206500bb5a99STobias Grosser       continue;
206600bb5a99STobias Grosser     }
206700bb5a99STobias Grosser 
2068fe74a7a1STobias Grosser     Value *Val = &*Arg;
2069fe74a7a1STobias Grosser 
2070fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
207100bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2072fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2073fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2074fe74a7a1STobias Grosser     }
2075fe74a7a1STobias Grosser 
2076fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
207700bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
207800bb5a99STobias Grosser 
207900bb5a99STobias Grosser     Arg++;
208000bb5a99STobias Grosser   }
208100bb5a99STobias Grosser }
208200bb5a99STobias Grosser 
208351dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
208451dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
208551dfc275STobias Grosser   auto Arg = FN->arg_begin();
208651dfc275STobias Grosser 
208751dfc275STobias Grosser   bool StoredScalar = false;
208851dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
208951dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
209051dfc275STobias Grosser       continue;
209151dfc275STobias Grosser 
209251dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2093206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2094206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
209551dfc275STobias Grosser     isl_id_free(Id);
209651dfc275STobias Grosser 
209751dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
209851dfc275STobias Grosser       Arg++;
209951dfc275STobias Grosser       continue;
210051dfc275STobias Grosser     }
210151dfc275STobias Grosser 
210251dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
210351dfc275STobias Grosser       Arg++;
210451dfc275STobias Grosser       continue;
210551dfc275STobias Grosser     }
210651dfc275STobias Grosser 
210751dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
210851dfc275STobias Grosser     Value *ArgPtr = &*Arg;
210951dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
211051dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
211151dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
211251dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
211351dfc275STobias Grosser     StoredScalar = true;
211451dfc275STobias Grosser 
211551dfc275STobias Grosser     Arg++;
211651dfc275STobias Grosser   }
211751dfc275STobias Grosser 
2118638316daSSiddharth Bhat   if (StoredScalar) {
211951dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
212051dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
212151dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
212251dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2123638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
212451dfc275STobias Grosser       BuildSuccessful = 0;
2125638316daSSiddharth Bhat       DEBUG(
2126638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2127638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2128638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2129638316daSSiddharth Bhat     }
2130638316daSSiddharth Bhat   }
213151dfc275STobias Grosser }
213251dfc275STobias Grosser 
2133b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2134b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2135b513b491STobias Grosser 
2136b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2137b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2138b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2139206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2140b513b491STobias Grosser 
2141f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2142b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2143b513b491STobias Grosser 
2144f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2145928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2146b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2147f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2148b513b491STobias Grosser       isl_val_free(Val);
2149b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2150928d7573STobias Grosser     }
2151928d7573STobias Grosser 
2152928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2153928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2154928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2155928d7573STobias Grosser       isl_val_free(Val);
2156b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2157b513b491STobias Grosser     }
2158b513b491STobias Grosser 
2159130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2160130ca30fSTobias Grosser     Value *Allocation;
2161130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2162130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2163130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2164130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2165130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2166f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2167f919d8b3STobias Grosser 
2168130ca30fSTobias Grosser       Allocation = GlobalVar;
2169130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2170130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2171130ca30fSTobias Grosser     } else {
2172130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2173130ca30fSTobias Grosser     }
21744d5a9172STobias Grosser     SAI =
21754d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2176b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2177130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2178130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2179b513b491STobias Grosser     KernelIds.push_back(Id);
2180b513b491STobias Grosser     IDToSAI[Id] = SAI;
2181b513b491STobias Grosser   }
2182b513b491STobias Grosser }
2183b513b491STobias Grosser 
2184f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2185f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2186f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
218779f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
218832837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
218917f01968SSiddharth Bhat 
219017f01968SSiddharth Bhat   switch (Arch) {
219117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
219217f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
219332837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
219417f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
219517f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
219632837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
219717f01968SSiddharth Bhat     break;
21982f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21992f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
22002f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
22012f3073b5SPhilipp Schaad     break;
22022f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22032f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
22042f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
22052f3073b5SPhilipp Schaad     break;
220617f01968SSiddharth Bhat   }
220732837fe3STobias Grosser 
2208edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
220932837fe3STobias Grosser 
221059ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
221132837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
221232837fe3STobias Grosser 
221359ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
221459ab0705STobias Grosser 
221532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
221632837fe3STobias Grosser   Builder.CreateRetVoid();
221732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2218472f9654STobias Grosser 
2219629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2220629109b6STobias Grosser 
222100bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2222b513b491STobias Grosser   createKernelVariables(Kernel, FN);
22232f3073b5SPhilipp Schaad 
22242f3073b5SPhilipp Schaad   switch (Arch) {
22252f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2226472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
22272f3073b5SPhilipp Schaad     break;
22282f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22292f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22302f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
22312f3073b5SPhilipp Schaad     break;
22322f3073b5SPhilipp Schaad   }
223332837fe3STobias Grosser }
223432837fe3STobias Grosser 
223574dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
223617f01968SSiddharth Bhat   llvm::Triple GPUTriple;
223717f01968SSiddharth Bhat 
223817f01968SSiddharth Bhat   switch (Arch) {
223917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
224017f01968SSiddharth Bhat     switch (Runtime) {
224117f01968SSiddharth Bhat     case GPURuntime::CUDA:
224217f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
224317f01968SSiddharth Bhat       break;
224417f01968SSiddharth Bhat     case GPURuntime::OpenCL:
224517f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
224617f01968SSiddharth Bhat       break;
224717f01968SSiddharth Bhat     }
224817f01968SSiddharth Bhat     break;
22492f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22502f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22512f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22522f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22532f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22542f3073b5SPhilipp Schaad     IROstream.flush();
22552f3073b5SPhilipp Schaad     return SPIRAssembly;
225617f01968SSiddharth Bhat   }
225717f01968SSiddharth Bhat 
225874dc3cb4STobias Grosser   std::string ErrMsg;
225974dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
226074dc3cb4STobias Grosser 
226174dc3cb4STobias Grosser   if (!GPUTarget) {
226274dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
226374dc3cb4STobias Grosser     return "";
226474dc3cb4STobias Grosser   }
226574dc3cb4STobias Grosser 
226674dc3cb4STobias Grosser   TargetOptions Options;
226774dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
226817f01968SSiddharth Bhat 
226917f01968SSiddharth Bhat   std::string subtarget;
227017f01968SSiddharth Bhat 
227117f01968SSiddharth Bhat   switch (Arch) {
227217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
227317f01968SSiddharth Bhat     subtarget = CudaVersion;
227417f01968SSiddharth Bhat     break;
22752f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22762f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22772f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
227817f01968SSiddharth Bhat   }
227917f01968SSiddharth Bhat 
228017f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
228117f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
228274dc3cb4STobias Grosser 
228374dc3cb4STobias Grosser   SmallString<0> ASMString;
228474dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
228574dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
228674dc3cb4STobias Grosser 
228774dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
228874dc3cb4STobias Grosser 
228974dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
229074dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
229174dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
229274dc3cb4STobias Grosser     return "";
229374dc3cb4STobias Grosser   }
229474dc3cb4STobias Grosser 
229574dc3cb4STobias Grosser   PM.run(*GPUModule);
229674dc3cb4STobias Grosser 
229774dc3cb4STobias Grosser   return ASMStream.str();
229874dc3cb4STobias Grosser }
229974dc3cb4STobias Grosser 
23008fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
2301*5b307cdbSTobias Grosser   bool RequiresLibDevice = false;
23028fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
23038fc6cdfbSTobias Grosser     if (!F.isDeclaration())
23048fc6cdfbSTobias Grosser       continue;
23058fc6cdfbSTobias Grosser 
23068fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
23078fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
23088fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
2309*5b307cdbSTobias Grosser       RequiresLibDevice = true;
23108fc6cdfbSTobias Grosser     }
23118fc6cdfbSTobias Grosser   }
23128fc6cdfbSTobias Grosser 
2313*5b307cdbSTobias Grosser   return RequiresLibDevice;
23148fc6cdfbSTobias Grosser }
23158fc6cdfbSTobias Grosser 
23168fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
23178fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
23188fc6cdfbSTobias Grosser     return;
23198fc6cdfbSTobias Grosser 
23208fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
23218fc6cdfbSTobias Grosser     SMDiagnostic Error;
23228fc6cdfbSTobias Grosser 
23238fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
23248fc6cdfbSTobias Grosser     auto LibDeviceModule =
23258fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
23268fc6cdfbSTobias Grosser 
23278fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
23288fc6cdfbSTobias Grosser       BuildSuccessful = false;
23298fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
23308fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
23318fc6cdfbSTobias Grosser                          "accordingly.\n");
23328fc6cdfbSTobias Grosser       return;
23338fc6cdfbSTobias Grosser     }
23348fc6cdfbSTobias Grosser 
23358fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23368fc6cdfbSTobias Grosser 
23378fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23388fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23398fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23408fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23418fc6cdfbSTobias Grosser   }
23428fc6cdfbSTobias Grosser }
23438fc6cdfbSTobias Grosser 
234457793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
234565d7f72fSSiddharth Bhat 
23465857b701STobias Grosser   if (verifyModule(*GPUModule)) {
234765d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
234865d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2349a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2350a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
235165d7f72fSSiddharth Bhat 
235265d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
235365d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
235465d7f72fSSiddharth Bhat 
23555857b701STobias Grosser     BuildSuccessful = false;
23565857b701STobias Grosser     return "";
23575857b701STobias Grosser   }
235832837fe3STobias Grosser 
23598fc6cdfbSTobias Grosser   addCUDALibDevice();
23608fc6cdfbSTobias Grosser 
236132837fe3STobias Grosser   if (DumpKernelIR)
236232837fe3STobias Grosser     outs() << *GPUModule << "\n";
236332837fe3STobias Grosser 
23642f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23659a18d559STobias Grosser     // Optimize module.
23669a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23679a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23689a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23699a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23709a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23719a18d559STobias Grosser     OptPasses.run(*GPUModule);
23722f3073b5SPhilipp Schaad   }
23739a18d559STobias Grosser 
237474dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
237574dc3cb4STobias Grosser 
237674dc3cb4STobias Grosser   if (DumpKernelASM)
237774dc3cb4STobias Grosser     outs() << Assembly << "\n";
237874dc3cb4STobias Grosser 
237932837fe3STobias Grosser   GPUModule.release();
2380472f9654STobias Grosser   KernelIDs.clear();
238157793596STobias Grosser 
238257793596STobias Grosser   return Assembly;
238332837fe3STobias Grosser }
2384eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2385eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2386eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2387eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2388eadf76d3SSiddharth Bhat ///
2389eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2390eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2391eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2392eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2393eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2394eadf76d3SSiddharth Bhat 
2395eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2396eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2397eadf76d3SSiddharth Bhat   }
2398eadf76d3SSiddharth Bhat   return List;
2399eadf76d3SSiddharth Bhat }
2400eadf76d3SSiddharth Bhat 
2401eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2402eadf76d3SSiddharth Bhat ///
2403eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2404eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2405eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2406eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2407eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2408eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2409eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2410eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2411eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2412eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2413eadf76d3SSiddharth Bhat ///                  affines.
2414eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2415eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2416eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2417eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2418eadf76d3SSiddharth Bhat 
2419eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2420eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2421eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2422eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2423eadf76d3SSiddharth Bhat   }
2424eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2425eadf76d3SSiddharth Bhat 
2426eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2427eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2428eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2429eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2430eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2431eadf76d3SSiddharth Bhat   }
2432eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2433eadf76d3SSiddharth Bhat }
243432837fe3STobias Grosser 
24359dfe4e7cSTobias Grosser namespace {
24369dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
24379dfe4e7cSTobias Grosser public:
24389dfe4e7cSTobias Grosser   static char ID;
24399dfe4e7cSTobias Grosser 
244017f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
244117f01968SSiddharth Bhat 
244217f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
244317f01968SSiddharth Bhat 
2444e938517eSTobias Grosser   /// The scop that is currently processed.
2445e938517eSTobias Grosser   Scop *S;
2446e938517eSTobias Grosser 
244738fc0aedSTobias Grosser   LoopInfo *LI;
244838fc0aedSTobias Grosser   DominatorTree *DT;
244938fc0aedSTobias Grosser   ScalarEvolution *SE;
245038fc0aedSTobias Grosser   const DataLayout *DL;
245138fc0aedSTobias Grosser   RegionInfo *RI;
245238fc0aedSTobias Grosser 
24539dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
24549dfe4e7cSTobias Grosser 
2455e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2456e938517eSTobias Grosser   ///
2457e938517eSTobias Grosser   /// @returns The compilation options.
2458e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2459e938517eSTobias Grosser     auto DebugOptions =
2460e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2461e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2462e938517eSTobias Grosser 
2463e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2464e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2465e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2466e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
24678950ceadSTobias Grosser     DebugOptions->verbose = false;
2468e938517eSTobias Grosser 
2469e938517eSTobias Grosser     Options->debug = DebugOptions;
2470e938517eSTobias Grosser 
24719e3db2b7SSiddharth Bhat     Options->group_chains = false;
2472e938517eSTobias Grosser     Options->reschedule = true;
2473e938517eSTobias Grosser     Options->scale_tile_loops = false;
2474e938517eSTobias Grosser     Options->wrap = false;
2475e938517eSTobias Grosser 
2476e938517eSTobias Grosser     Options->non_negative_parameters = false;
2477e938517eSTobias Grosser     Options->ctx = nullptr;
2478e938517eSTobias Grosser     Options->sizes = nullptr;
2479e938517eSTobias Grosser 
24809e3db2b7SSiddharth Bhat     Options->tile = true;
24814eaedde5STobias Grosser     Options->tile_size = 32;
24824eaedde5STobias Grosser 
24839e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
24849e3db2b7SSiddharth Bhat 
2485130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2486b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2487b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2488e938517eSTobias Grosser 
2489e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2490e938517eSTobias Grosser     Options->openmp = false;
2491e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24929e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2493e938517eSTobias Grosser 
24949e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
24959e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
24969e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24979e3db2b7SSiddharth Bhat 
24989e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24999e3db2b7SSiddharth Bhat     Options->hybrid = false;
2500e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2501e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2502e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2503e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2504e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2505e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2506e938517eSTobias Grosser 
2507e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2508e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2509e938517eSTobias Grosser 
2510e938517eSTobias Grosser     return Options;
2511e938517eSTobias Grosser   }
2512e938517eSTobias Grosser 
2513f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2514f384594dSTobias Grosser   ///
2515f384594dSTobias Grosser   /// Instead of a normal access of the form:
2516f384594dSTobias Grosser   ///
2517f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2518f384594dSTobias Grosser   ///
2519f384594dSTobias Grosser   /// a tagged access has the form
2520f384594dSTobias Grosser   ///
2521f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2522f384594dSTobias Grosser   ///
2523f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2524f384594dSTobias Grosser   /// triggered the access.
2525f384594dSTobias Grosser   ///
2526f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2527f384594dSTobias Grosser   ///
2528f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2529f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2530f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2531f384594dSTobias Grosser 
2532f384594dSTobias Grosser     for (auto &Stmt : *S)
2533f384594dSTobias Grosser       for (auto &Acc : Stmt)
2534f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
25351515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2536f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2537f384594dSTobias Grosser 
2538f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2539f384594dSTobias Grosser           Space = isl_space_range(Space);
2540f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2541fe46c3ffSTobias Grosser           Space =
2542fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2543f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2544f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2545f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2546f384594dSTobias Grosser         }
2547f384594dSTobias Grosser 
2548f384594dSTobias Grosser     return Accesses;
2549f384594dSTobias Grosser   }
2550f384594dSTobias Grosser 
2551f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2552f384594dSTobias Grosser   ///
2553f384594dSTobias Grosser   /// @see getTaggedAccesses
2554f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2555f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2556f384594dSTobias Grosser   }
2557f384594dSTobias Grosser 
2558f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2559f384594dSTobias Grosser   ///
2560f384594dSTobias Grosser   /// @see getTaggedAccesses
2561f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2562f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2563f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2564f384594dSTobias Grosser   }
2565f384594dSTobias Grosser 
2566f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2567f384594dSTobias Grosser   ///
2568f384594dSTobias Grosser   /// @see getTaggedAccesses
2569f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2570f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2571f384594dSTobias Grosser   }
2572f384594dSTobias Grosser 
2573aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2574aef5196fSTobias Grosser   ///
2575aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2576aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2577aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2578aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2579aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2580aef5196fSTobias Grosser   /// the data format that ppcg expects.
2581aef5196fSTobias Grosser   ///
2582aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2583aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2584aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2585bd81a7eeSTobias Grosser         S->getIslCtx(),
2586bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2587aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2588aef5196fSTobias Grosser 
258925271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
259025271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2591aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2592aef5196fSTobias Grosser     }
2593aef5196fSTobias Grosser 
2594aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
259577eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2596aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2597aef5196fSTobias Grosser     }
2598aef5196fSTobias Grosser 
2599aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2600aef5196fSTobias Grosser 
2601aef5196fSTobias Grosser     return Names;
2602aef5196fSTobias Grosser   }
2603aef5196fSTobias Grosser 
2604e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2605e938517eSTobias Grosser   ///
2606f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2607f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2608f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2609f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2610e938517eSTobias Grosser   ///
2611e938517eSTobias Grosser   /// @returns A new ppcg scop.
2612e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
26139e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
26149e3db2b7SSiddharth Bhat 
2615e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2616e938517eSTobias Grosser 
2617e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2618a82f2d26SSiddharth Bhat     // enable live range reordering
2619a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2620e938517eSTobias Grosser 
2621e938517eSTobias Grosser     PPCGScop->start = 0;
2622e938517eSTobias Grosser     PPCGScop->end = 0;
2623e938517eSTobias Grosser 
2624f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2625f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
26269e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
26279e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2628f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2629f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2630e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2631f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2632f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2633f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2634f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2635e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
26369e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
26379e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
26389e3db2b7SSiddharth Bhat 
2639e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2640a82f2d26SSiddharth Bhat     PPCGScop->independence =
2641a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2642e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2643e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2644e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2645e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2646e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2647e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2648e938517eSTobias Grosser 
2649f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2650a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2651a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2652a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2653a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2654a82f2d26SSiddharth Bhat 
2655a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2656e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2657e938517eSTobias Grosser 
2658f384594dSTobias Grosser     compute_tagger(PPCGScop);
2659f384594dSTobias Grosser     compute_dependences(PPCGScop);
26609e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2661f384594dSTobias Grosser 
2662e938517eSTobias Grosser     return PPCGScop;
2663e938517eSTobias Grosser   }
2664e938517eSTobias Grosser 
2665a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
266660f63b49STobias Grosser   ///
266760f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
266860f63b49STobias Grosser   ///
266960f63b49STobias Grosser   /// @returns A list of array accesses.
267060f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
267160f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
267260f63b49STobias Grosser 
267360f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
267460f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
267560f63b49STobias Grosser       Access->read = Acc->isRead();
267660f63b49STobias Grosser       Access->write = Acc->isWrite();
26771515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
267860f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
267960f63b49STobias Grosser       Space = isl_space_range(Space);
268060f63b49STobias Grosser       Space = isl_space_from_range(Space);
2681fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
268260f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
268360f63b49STobias Grosser       Access->tagged_access =
26841515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2685b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2686fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
268760f63b49STobias Grosser       Access->next = Accesses;
2688b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
268960f63b49STobias Grosser       Accesses = Access;
269060f63b49STobias Grosser     }
269160f63b49STobias Grosser 
269260f63b49STobias Grosser     return Accesses;
269360f63b49STobias Grosser   }
269460f63b49STobias Grosser 
269569b46751STobias Grosser   /// Collect the list of GPU statements.
269669b46751STobias Grosser   ///
269769b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
269869b46751STobias Grosser   /// as well as a list with all memory accesses.
269969b46751STobias Grosser   ///
270069b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
270169b46751STobias Grosser   ///
270269b46751STobias Grosser   /// @returns A linked-list of statements.
270369b46751STobias Grosser   gpu_stmt *getStatements() {
270469b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
270569b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
270669b46751STobias Grosser 
270769b46751STobias Grosser     int i = 0;
270869b46751STobias Grosser     for (auto &Stmt : *S) {
270969b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
271069b46751STobias Grosser 
271169b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
271269b46751STobias Grosser 
271369b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
271469b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
271560f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
271669b46751STobias Grosser       i++;
271769b46751STobias Grosser     }
271869b46751STobias Grosser 
271969b46751STobias Grosser     return Stmts;
272069b46751STobias Grosser   }
272169b46751STobias Grosser 
272260f63b49STobias Grosser   /// Derive the extent of an array.
272360f63b49STobias Grosser   ///
2724d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2725d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2726d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2727d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2728d58acf86STobias Grosser   /// subscript value for the first dimension.
272960f63b49STobias Grosser   ///
273060f63b49STobias Grosser   /// @param Array The array to derive the extent for.
273160f63b49STobias Grosser   ///
273260f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
273360f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2734d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
273560f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
273660f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2737d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
273860f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2739d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2740d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2741d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2742d58acf86STobias Grosser 
2743d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2744d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
274577eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2746d58acf86STobias Grosser     }
2747d58acf86STobias Grosser 
2748d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2749d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
275077eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2751d58acf86STobias Grosser     }
2752d58acf86STobias Grosser 
275360f63b49STobias Grosser     isl_set *AccessSet =
275477eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
275560f63b49STobias Grosser 
2756d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
275777eef90fSTobias Grosser     isl_local_space *LS =
275877eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2759d58acf86STobias Grosser 
2760d58acf86STobias Grosser     isl_pw_aff *Val =
2761d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2762d58acf86STobias Grosser 
2763d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2764d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2765d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2766d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2767d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2768d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
276977eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
277077eef90fSTobias Grosser                                        Array->getBasePtrId().release());
277177eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
277277eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2773d58acf86STobias Grosser 
277477eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2775d58acf86STobias Grosser 
2776d58acf86STobias Grosser     Extent = isl_set_intersect(
2777d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2778d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2779d58acf86STobias Grosser 
2780d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2781d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2782d58acf86STobias Grosser 
2783b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2784d58acf86STobias Grosser       isl_pw_aff *PwAff =
278577eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2786b7f68b8cSSiddharth Bhat 
2787b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2788b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2789b7f68b8cSSiddharth Bhat       if (!PwAff) {
2790b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2791b7f68b8cSSiddharth Bhat         continue;
2792b7f68b8cSSiddharth Bhat       }
2793b7f68b8cSSiddharth Bhat 
2794d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
279577eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
279677eef90fSTobias Grosser           i));
2797d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2798d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2799d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2800d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2801d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2802d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2803d58acf86STobias Grosser     }
2804d58acf86STobias Grosser 
2805d58acf86STobias Grosser     return Extent;
280660f63b49STobias Grosser   }
280760f63b49STobias Grosser 
280860f63b49STobias Grosser   /// Derive the bounds of an array.
280960f63b49STobias Grosser   ///
281060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
281160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
281260f63b49STobias Grosser   /// ScopArrayInfo.
281360f63b49STobias Grosser   ///
281460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
281560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
281660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2817eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
28189e3db2b7SSiddharth Bhat 
281960f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
282002293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
282102293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
282202293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
282302293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
282402293ed7STobias Grosser         isl_set_free(Dom);
28259e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2826eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
282702293ed7STobias Grosser       } else {
282860f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
282960f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
283060f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
283160f63b49STobias Grosser         isl_set_free(Dom);
283260f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
283302293ed7STobias Grosser         isl_local_space *LS =
283402293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
283560f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
283660f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
283760f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
283860f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
2839eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
284060f63b49STobias Grosser       }
284102293ed7STobias Grosser     }
284260f63b49STobias Grosser 
284360f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
284477eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
284560f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
284660f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
284760f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2848eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
284960f63b49STobias Grosser     }
28509e3db2b7SSiddharth Bhat 
2851eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2852eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2853eadf76d3SSiddharth Bhat     /// appropriate space.
2854eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2855eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2856eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2857eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2858eadf76d3SSiddharth Bhat     isl_space *SeedAlignSpace = S->getParamSpace();
2859eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2860eadf76d3SSiddharth Bhat 
2861eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
2862eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
2863eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
2864eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
2865eadf76d3SSiddharth Bhat 
2866eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
2867eadf76d3SSiddharth Bhat 
2868eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
2869eadf76d3SSiddharth Bhat         createPwAffList(S->getIslCtx(), std::move(AlignedBounds));
2870eadf76d3SSiddharth Bhat 
28719e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2872eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
28739e3db2b7SSiddharth Bhat 
28749e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
28759e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
28769e3db2b7SSiddharth Bhat 
28779e3db2b7SSiddharth Bhat     PPCGArray.bound =
28789e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
28799e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
288060f63b49STobias Grosser   }
288160f63b49STobias Grosser 
288260f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
288360f63b49STobias Grosser   ///
288460f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
288543f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
288643f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
288760f63b49STobias Grosser     int i = 0;
288843f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
288960f63b49STobias Grosser       std::string TypeName;
289060f63b49STobias Grosser       raw_string_ostream OS(TypeName);
289160f63b49STobias Grosser 
289260f63b49STobias Grosser       OS << *Array->getElementType();
289360f63b49STobias Grosser       TypeName = OS.str();
289460f63b49STobias Grosser 
289560f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
289660f63b49STobias Grosser 
289777eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
289860f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
289960f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
290060f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
290160f63b49STobias Grosser       PPCGArray.extent = nullptr;
290260f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
290360f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
290460f63b49STobias Grosser       PPCGArray.n_ref = 0;
290560f63b49STobias Grosser       PPCGArray.refs = nullptr;
290660f63b49STobias Grosser       PPCGArray.accessed = true;
2907fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2908fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
290960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
291060f63b49STobias Grosser       PPCGArray.local = false;
291160f63b49STobias Grosser       PPCGArray.declare_local = false;
291260f63b49STobias Grosser       PPCGArray.global = false;
291360f63b49STobias Grosser       PPCGArray.linearize = false;
291460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
291513c78e4dSTobias Grosser       PPCGArray.user = Array;
291660f63b49STobias Grosser 
29179e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
291860f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
29192d010dafSTobias Grosser       i++;
2920b9fc860aSTobias Grosser 
2921b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
292260f63b49STobias Grosser     }
292360f63b49STobias Grosser   }
292460f63b49STobias Grosser 
292560f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
292660f63b49STobias Grosser   ///
292760f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
292860f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
292960f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
293060f63b49STobias Grosser 
2931d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
293277eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
293360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
293460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
293560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
293660f63b49STobias Grosser     }
293760f63b49STobias Grosser 
293860f63b49STobias Grosser     return Maps;
293960f63b49STobias Grosser   }
294060f63b49STobias Grosser 
2941e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2942e938517eSTobias Grosser   ///
2943a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2944e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2945e938517eSTobias Grosser 
2946e938517eSTobias Grosser     if (!PPCGScop)
2947e938517eSTobias Grosser       return nullptr;
2948e938517eSTobias Grosser 
2949e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2950e938517eSTobias Grosser 
2951e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2952e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2953aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
295460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
295560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
295660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
295760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
295860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
295960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
296060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
29619e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2962e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2963a82f2d26SSiddharth Bhat 
2964a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2965a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2966a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2967a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2968a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2969a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
297069b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
297169b46751STobias Grosser     PPCGProg->stmts = getStatements();
297243f178bbSSiddharth Bhat 
297343f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
297443f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
297543f178bbSSiddharth Bhat     // empty arrays:
297643f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
297743f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
297843f178bbSSiddharth Bhat     auto ValidSAIsRange =
297943f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
298043f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
298143f178bbSSiddharth Bhat         });
298243f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
298343f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
298443f178bbSSiddharth Bhat 
298543f178bbSSiddharth Bhat     PPCGProg->n_array =
298643f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
298760f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
298860f63b49STobias Grosser                                        PPCGProg->n_array);
298960f63b49STobias Grosser 
299043f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2991e938517eSTobias Grosser 
2992d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2993e938517eSTobias Grosser     return PPCGProg;
2994e938517eSTobias Grosser   }
2995e938517eSTobias Grosser 
299669b46751STobias Grosser   struct PrintGPUUserData {
299769b46751STobias Grosser     struct cuda_info *CudaInfo;
299869b46751STobias Grosser     struct gpu_prog *PPCGProg;
299969b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
300069b46751STobias Grosser   };
300169b46751STobias Grosser 
300269b46751STobias Grosser   /// Print a user statement node in the host code.
300369b46751STobias Grosser   ///
300469b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
300569b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
300669b46751STobias Grosser   /// host ast.
300769b46751STobias Grosser   ///
300869b46751STobias Grosser   /// @param P The printer to print to
300969b46751STobias Grosser   /// @param Options The printing options to use
301069b46751STobias Grosser   /// @param Node The node to print
301169b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
301269b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
301369b46751STobias Grosser   ///
301469b46751STobias Grosser   /// @returns A printer to which the output has been printed.
301569b46751STobias Grosser   static __isl_give isl_printer *
301669b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
301769b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
301869b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
301969b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
302069b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
302169b46751STobias Grosser 
302269b46751STobias Grosser     if (Id) {
302320251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
302420251734STobias Grosser 
302520251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
302620251734STobias Grosser       // otherwise try to call pet functionality that is not available in
302720251734STobias Grosser       // Polly.
302820251734STobias Grosser       if (IsUser) {
302920251734STobias Grosser         P = isl_printer_start_line(P);
303020251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
303120251734STobias Grosser         P = isl_printer_end_line(P);
303220251734STobias Grosser         isl_id_free(Id);
303320251734STobias Grosser         isl_ast_print_options_free(Options);
303420251734STobias Grosser         return P;
303520251734STobias Grosser       }
303620251734STobias Grosser 
303769b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
303869b46751STobias Grosser       isl_id_free(Id);
303969b46751STobias Grosser       Data->Kernels.push_back(Kernel);
304069b46751STobias Grosser     }
304169b46751STobias Grosser 
304269b46751STobias Grosser     return print_host_user(P, Options, Node, User);
304369b46751STobias Grosser   }
304469b46751STobias Grosser 
304569b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
304669b46751STobias Grosser   ///
304769b46751STobias Grosser   /// @param Kernel The kernel to print
304869b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
304969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
305069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
305169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
305269b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
305369b46751STobias Grosser     char *String = isl_printer_get_str(P);
305469b46751STobias Grosser     printf("%s\n", String);
305569b46751STobias Grosser     free(String);
305669b46751STobias Grosser     isl_printer_free(P);
305769b46751STobias Grosser   }
305869b46751STobias Grosser 
305969b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
306069b46751STobias Grosser   ///
306169b46751STobias Grosser   /// @param Tree An AST describing GPU code
306269b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
306369b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
306469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
306569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
306669b46751STobias Grosser 
306769b46751STobias Grosser     PrintGPUUserData Data;
306869b46751STobias Grosser     Data.PPCGProg = PPCGProg;
306969b46751STobias Grosser 
307069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
307169b46751STobias Grosser     Options =
307269b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
307369b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
307469b46751STobias Grosser     char *String = isl_printer_get_str(P);
307569b46751STobias Grosser     printf("# host\n");
307669b46751STobias Grosser     printf("%s\n", String);
307769b46751STobias Grosser     free(String);
307869b46751STobias Grosser     isl_printer_free(P);
307969b46751STobias Grosser 
308069b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
308169b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
308269b46751STobias Grosser       printKernel(Kernel);
308369b46751STobias Grosser     }
308469b46751STobias Grosser   }
308569b46751STobias Grosser 
3086f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3087f384594dSTobias Grosser   //
3088f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3089f384594dSTobias Grosser   //
3090f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3091f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3092f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3093f384594dSTobias Grosser   //
3094f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3095f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3096f384594dSTobias Grosser   // strategy directly from this pass.
3097f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3098f384594dSTobias Grosser 
3099f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3100f384594dSTobias Grosser 
3101f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3102f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3103f384594dSTobias Grosser     PPCGGen->print = nullptr;
3104f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
310560c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3106f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3107f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3108f384594dSTobias Grosser     PPCGGen->types.n = 0;
3109f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3110f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3111f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3112f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3113f384594dSTobias Grosser 
3114f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3115f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3116f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
31172341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3118f384594dSTobias Grosser 
3119f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3120f384594dSTobias Grosser 
3121aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3122aef5196fSTobias Grosser 
3123b5563c68STobias Grosser     Schedule =
3124b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3125b5563c68STobias Grosser 
312669b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3127aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3128638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3129638316daSSiddharth Bhat                    << " does not have permutable bands. Bailing out\n";);
313069b46751STobias Grosser     } else {
3131aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
313269b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
313369b46751STobias Grosser     }
3134aef5196fSTobias Grosser 
3135f384594dSTobias Grosser     if (DumpSchedule) {
3136f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3137f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3138f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3139f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3140f384594dSTobias Grosser       if (Schedule)
3141f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3142f384594dSTobias Grosser       else
3143f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3144f384594dSTobias Grosser 
3145f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3146f384594dSTobias Grosser       isl_printer_free(P);
3147f384594dSTobias Grosser     }
3148f384594dSTobias Grosser 
314969b46751STobias Grosser     if (DumpCode) {
315069b46751STobias Grosser       printf("Code\n");
315169b46751STobias Grosser       printf("====\n");
315269b46751STobias Grosser       if (PPCGGen->tree)
315369b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
315469b46751STobias Grosser       else
315569b46751STobias Grosser         printf("No code generated\n");
315669b46751STobias Grosser     }
315769b46751STobias Grosser 
3158f384594dSTobias Grosser     isl_schedule_free(Schedule);
3159f384594dSTobias Grosser 
3160f384594dSTobias Grosser     return PPCGGen;
3161f384594dSTobias Grosser   }
3162f384594dSTobias Grosser 
3163f384594dSTobias Grosser   /// Free gpu_gen structure.
3164f384594dSTobias Grosser   ///
3165f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3166f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3167f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3168f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3169f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3170f384594dSTobias Grosser     free(PPCGGen);
3171f384594dSTobias Grosser   }
3172f384594dSTobias Grosser 
3173b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3174b307ed4dSTobias Grosser   ///
3175b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3176b307ed4dSTobias Grosser   /// ourselves.
3177b307ed4dSTobias Grosser   ///
3178b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3179b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3180b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3181b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3182b307ed4dSTobias Grosser     free(PPCGScop->options);
3183b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3184b307ed4dSTobias Grosser   }
3185b307ed4dSTobias Grosser 
318682f2af35STobias Grosser   /// Approximate the number of points in the set.
318782f2af35STobias Grosser   ///
318882f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
318982f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
319082f2af35STobias Grosser   ///
319182f2af35STobias Grosser   /// @param Set   The set to count.
319282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
319382f2af35STobias Grosser   ///              expression.
319482f2af35STobias Grosser   ///
319582f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
319682f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
319782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
319882f2af35STobias Grosser 
319982f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
320082f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
320182f2af35STobias Grosser 
320282f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
320382f2af35STobias Grosser     Space = isl_space_params(Space);
320482f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
320582f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
320682f2af35STobias Grosser 
320782f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
320882f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
320982f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
321082f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
321182f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
321282f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
321382f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
321482f2af35STobias Grosser     }
321582f2af35STobias Grosser 
321682f2af35STobias Grosser     isl_set_free(Set);
321782f2af35STobias Grosser     isl_pw_aff_free(OneAff);
321882f2af35STobias Grosser 
321982f2af35STobias Grosser     return Expr;
322082f2af35STobias Grosser   }
322182f2af35STobias Grosser 
322282f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
322382f2af35STobias Grosser   /// statement.
322482f2af35STobias Grosser   ///
322582f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
322682f2af35STobias Grosser   ///              instructions.
322782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
322882f2af35STobias Grosser   ///              expression.
322982f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
323082f2af35STobias Grosser   ///          by @p Stmt.
323182f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
323282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
323382f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
323482f2af35STobias Grosser 
323582f2af35STobias Grosser     long InstCount = 0;
323682f2af35STobias Grosser 
323782f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
323882f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
323982f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
324082f2af35STobias Grosser     } else {
324182f2af35STobias Grosser       auto *R = Stmt.getRegion();
324282f2af35STobias Grosser 
324382f2af35STobias Grosser       for (auto *BB : R->blocks()) {
324482f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
324582f2af35STobias Grosser       }
324682f2af35STobias Grosser     }
324782f2af35STobias Grosser 
324882f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
324982f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
325082f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
325182f2af35STobias Grosser   }
325282f2af35STobias Grosser 
325382f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
325482f2af35STobias Grosser   ///
325582f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
325682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
325782f2af35STobias Grosser   ///              expression.
325882f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
325982f2af35STobias Grosser   ///          in @p S.
326082f2af35STobias Grosser   __isl_give isl_ast_expr *
326182f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
326282f2af35STobias Grosser     isl_ast_expr *Instructions;
326382f2af35STobias Grosser 
326482f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
326582f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
326682f2af35STobias Grosser 
326782f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
326882f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
326982f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
327082f2af35STobias Grosser     }
327182f2af35STobias Grosser     return Instructions;
327282f2af35STobias Grosser   }
327382f2af35STobias Grosser 
327482f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
327582f2af35STobias Grosser   ///
327682f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
327782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
327882f2af35STobias Grosser   ///              expression.
327982f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
328082f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
328182f2af35STobias Grosser   __isl_give isl_ast_expr *
328282f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
328382f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
328482f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
328582f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
328682f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
328782f2af35STobias Grosser   }
328882f2af35STobias Grosser 
3289f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3290f291c8d5SSiddharth Bhat   /// kernels.
3291f291c8d5SSiddharth Bhat   ///
3292f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3293f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
32948fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
32958fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3296f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3297f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
32988fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
32998fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3300f291c8d5SSiddharth Bhat         continue;
3301f291c8d5SSiddharth Bhat       }
3302f291c8d5SSiddharth Bhat 
3303bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3304bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3305bccaea57SSiddharth Bhat         if (!p)
3306bccaea57SSiddharth Bhat           continue;
3307bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3308bccaea57SSiddharth Bhat           return true;
3309bccaea57SSiddharth Bhat       }
3310f291c8d5SSiddharth Bhat     }
3311bccaea57SSiddharth Bhat     return false;
3312bccaea57SSiddharth Bhat   }
3313bccaea57SSiddharth Bhat 
3314f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
33158fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3316bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3317bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
33188fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
33198fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3320bccaea57SSiddharth Bhat           return true;
3321bccaea57SSiddharth Bhat       } else {
3322bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3323bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3324bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
33258fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3326bccaea57SSiddharth Bhat             return true;
3327bccaea57SSiddharth Bhat       }
3328bccaea57SSiddharth Bhat     }
3329bccaea57SSiddharth Bhat     return false;
3330bccaea57SSiddharth Bhat   }
3331bccaea57SSiddharth Bhat 
333238fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
333338fc0aedSTobias Grosser   ///
333432837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
333532837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
333632837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
333738fc0aedSTobias Grosser     ScopAnnotator Annotator;
333838fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
333938fc0aedSTobias Grosser 
334038fc0aedSTobias Grosser     Region *R = &S->getRegion();
334138fc0aedSTobias Grosser 
334238fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
334338fc0aedSTobias Grosser 
334438fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
334538fc0aedSTobias Grosser 
334638fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
334738fc0aedSTobias Grosser 
334838fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
334938fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
335038fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
335138fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
335238fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
335338fc0aedSTobias Grosser     // code generating this scop.
335403346c27SSiddharth Bhat     BBPair StartExitBlocks;
335503346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
335603346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
33572d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3358256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
335938fc0aedSTobias Grosser 
336003346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
336103346c27SSiddharth Bhat 
33622d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
336317f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3364acf80064SEli Friedman 
336538fc0aedSTobias Grosser     // TODO: Handle LICM
336638fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
336738fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
336838fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3369cb1aef8dSTobias Grosser 
3370cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
33712b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
337282f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
337382f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3374cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3375cb1aef8dSTobias Grosser 
33769e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
33779e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
33784ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
33794ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
33804ebeb356SSiddharth Bhat                          S->getFunction().getName() +
33814ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
33829e3db2b7SSiddharth Bhat 
3383cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3384cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3385cb1aef8dSTobias Grosser 
338638fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3387fa7b0802STobias Grosser 
338838fc0aedSTobias Grosser     NodeBuilder.create(Root);
33895857b701STobias Grosser 
3390bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3391bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3392de244eb4STobias Grosser     /// point in running it on a GPU.
3393bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
339403346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3395bc653f20STobias Grosser 
33965857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
339703346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
339838fc0aedSTobias Grosser   }
339938fc0aedSTobias Grosser 
3400e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3401e938517eSTobias Grosser     S = &CurrentScop;
340238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
340338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
340438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
34057b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
340638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3407e938517eSTobias Grosser 
3408f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3409f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3410f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3411bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3412bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
34138fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
34148fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3415f291c8d5SSiddharth Bhat       DEBUG(
3416638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3417638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3418f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3419bccaea57SSiddharth Bhat       return false;
3420f291c8d5SSiddharth Bhat     }
3421bccaea57SSiddharth Bhat 
3422e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3423e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3424f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
342538fc0aedSTobias Grosser 
342602ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
342732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
342802ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3429638316daSSiddharth Bhat     } else {
3430638316daSSiddharth Bhat       DEBUG(dbgs() << getUniqueScopName(S)
3431638316daSSiddharth Bhat                    << " has empty PPCGGen->tree. Bailing out.\n");
343202ca346eSSingapuram Sanjay Srivallabh     }
343338fc0aedSTobias Grosser 
3434b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3435f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3436e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3437e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3438e938517eSTobias Grosser 
3439e938517eSTobias Grosser     return true;
3440e938517eSTobias Grosser   }
34419dfe4e7cSTobias Grosser 
34429dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
34439dfe4e7cSTobias Grosser 
34449dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
34459dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
34469dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
34479dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
34485cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
34499dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
34509dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
34519dfe4e7cSTobias Grosser 
34529dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
34539dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
34549dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
34559dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
34569dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
34575cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
34589dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
34599dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
34609dfe4e7cSTobias Grosser 
34619dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
34629dfe4e7cSTobias Grosser     //        region tree.
34639dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
34649dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
34659dfe4e7cSTobias Grosser   }
34669dfe4e7cSTobias Grosser };
346724222c73STobias Grosser } // namespace
34689dfe4e7cSTobias Grosser 
34699dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
34709dfe4e7cSTobias Grosser 
347117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
347217f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
347317f01968SSiddharth Bhat   generator->Runtime = Runtime;
347417f01968SSiddharth Bhat   generator->Architecture = Arch;
347517f01968SSiddharth Bhat   return generator;
347617f01968SSiddharth Bhat }
34779dfe4e7cSTobias Grosser 
34789dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
34799dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
34809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
34819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
34829dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
34839dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
34849dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
34855cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
34869dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
34879dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3488