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 
122a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
123a82f2d26SSiddharth Bhat /// used by live range reordering.
124a82f2d26SSiddharth Bhat ///
125a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
126a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
127a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
128a82f2d26SSiddharth Bhat struct MustKillsInfo {
129a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
130a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
131a82f2d26SSiddharth Bhat   ///
132a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
133a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
134a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
135a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
136a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
137a82f2d26SSiddharth Bhat   /// killed.
138a82f2d26SSiddharth Bhat   ///
139edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
140edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
141edfef5aeSSiddharth Bhat   ///     consequently all be killed.
142edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
143edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
144edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
145a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
146a82f2d26SSiddharth Bhat 
1479e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1489e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1499e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1509e3db2b7SSiddharth Bhat 
1519e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
152a82f2d26SSiddharth Bhat };
153a82f2d26SSiddharth Bhat 
154761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
155761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
156761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
157761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
158761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
159761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
160761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
161761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
162761e5b93SSiddharth Bhat 
163761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
164761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
165761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
166761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
167761e5b93SSiddharth Bhat     if (!R.contains(I))
168761e5b93SSiddharth Bhat       return false;
169761e5b93SSiddharth Bhat   }
170761e5b93SSiddharth Bhat   return true;
171761e5b93SSiddharth Bhat }
172761e5b93SSiddharth Bhat 
173a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
174a82f2d26SSiddharth Bhat ///
175a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
176a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
177a82f2d26SSiddharth Bhat /// PPCG.
178a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
179a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
180a82f2d26SSiddharth Bhat   MustKillsInfo Info;
181a82f2d26SSiddharth Bhat 
182761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
183761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
184761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
185a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
186a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
187761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
188761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
18977eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
190a82f2d26SSiddharth Bhat   }
191a82f2d26SSiddharth Bhat 
192a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
1939e3db2b7SSiddharth Bhat   Info.MustKills = isl::union_map::empty(isl::space(ParamSpace));
194a82f2d26SSiddharth Bhat 
195a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
196a82f2d26SSiddharth Bhat   // schedule:
197a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
198a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
199a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
200a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
201a82f2d26SSiddharth Bhat 
202edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
203a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
204edfef5aeSSiddharth Bhat         S.getIslCtx(),
205edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
206a82f2d26SSiddharth Bhat 
207a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
208a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
209edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
210a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
211edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
212edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
213edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
214edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
215a82f2d26SSiddharth Bhat     //
216a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
217a82f2d26SSiddharth Bhat     // TaggedMustKill:
218edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
219a82f2d26SSiddharth Bhat 
220edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
221edfef5aeSSiddharth Bhat     isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace));
222edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
223edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
224a82f2d26SSiddharth Bhat 
225a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
226edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
227edfef5aeSSiddharth Bhat         nullptr);
228a82f2d26SSiddharth Bhat 
229edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
230edfef5aeSSiddharth Bhat     isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace));
231edfef5aeSSiddharth Bhat     PhantomRefToScalar =
232edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
233edfef5aeSSiddharth Bhat     PhantomRefToScalar =
234edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
235a82f2d26SSiddharth Bhat 
236edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
237edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
238a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
239a82f2d26SSiddharth Bhat 
2409e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2419e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2429e3db2b7SSiddharth Bhat 
243a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
244a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
245a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
246a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
247a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
248a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
249a82f2d26SSiddharth Bhat 
250a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
251a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
252a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
253a82f2d26SSiddharth Bhat     else
254a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
255a82f2d26SSiddharth Bhat   }
256a82f2d26SSiddharth Bhat 
257a82f2d26SSiddharth Bhat   return Info;
258a82f2d26SSiddharth Bhat }
259a82f2d26SSiddharth Bhat 
26060c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
26160c60025STobias Grosser ///
26260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
26360c60025STobias Grosser /// of the scheduled ScopStmts.
26460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
26535de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
26660c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
26760c60025STobias Grosser                                        isl_id *Id, void *User),
26860c60025STobias Grosser     void *UserIndex,
26960c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
270edb885cbSTobias Grosser     void *UserExpr) {
27160c60025STobias Grosser 
272edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
27360c60025STobias Grosser 
27435de9009SSiddharth Bhat   if (!Stmt || !Build_C)
275edb885cbSTobias Grosser     return NULL;
276edb885cbSTobias Grosser 
27735de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
27835de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
27935de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
280edb885cbSTobias Grosser 
281edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
28235de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
28335de9009SSiddharth Bhat     AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain()));
28435de9009SSiddharth Bhat 
28535de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
28635de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
28735de9009SSiddharth Bhat 
28835de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
28935de9009SSiddharth Bhat     MPA = MPA.coalesce();
29035de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
29135de9009SSiddharth Bhat 
29235de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
29335de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
29435de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
295edb885cbSTobias Grosser   }
296edb885cbSTobias Grosser 
29735de9009SSiddharth Bhat   return RefToExpr.release();
29860c60025STobias Grosser }
299f384594dSTobias Grosser 
300a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
301a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
302a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
303a90be207SSiddharth Bhat   if (bytes == 0)
304a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
305a90be207SSiddharth Bhat   return bytes;
306a90be207SSiddharth Bhat }
307a90be207SSiddharth Bhat 
30838fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
30938fc0aedSTobias Grosser ///
31038fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
311a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
31238fc0aedSTobias Grosser /// for generating GPU specific user nodes.
31338fc0aedSTobias Grosser ///
31438fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
31538fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
31638fc0aedSTobias Grosser public:
3172d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
31838fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
319acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
32017f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3212d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
32217f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
323edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
324edb885cbSTobias Grosser   }
32538fc0aedSTobias Grosser 
326fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
327fa7b0802STobias Grosser   void initializeAfterRTH();
328fa7b0802STobias Grosser 
329fa7b0802STobias Grosser   /// Finalize the generated scop.
330fa7b0802STobias Grosser   virtual void finalize();
331fa7b0802STobias Grosser 
3325857b701STobias Grosser   /// Track if the full build process was successful.
3335857b701STobias Grosser   ///
3345857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3355857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3365857b701STobias Grosser   bool BuildSuccessful = true;
3375857b701STobias Grosser 
338bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
339bc653f20STobias Grosser   unsigned DeepestSequential = 0;
340bc653f20STobias Grosser 
341bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
342bc653f20STobias Grosser   unsigned DeepestParallel = 0;
343bc653f20STobias Grosser 
34479f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
34579f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
34679f13b9aSSingapuram Sanjay Srivallabh 
34738fc0aedSTobias Grosser private:
34874dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
34974dc3cb4STobias Grosser   ///
35074dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
35174dc3cb4STobias Grosser   /// more.
35274dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
35374dc3cb4STobias Grosser 
35413c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
35513c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3567287aeddSTobias Grosser 
357fa7b0802STobias Grosser   /// The current GPU context.
358fa7b0802STobias Grosser   Value *GPUContext;
359fa7b0802STobias Grosser 
360b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
361b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
362b513b491STobias Grosser 
36332837fe3STobias Grosser   /// A module containing GPU code.
36432837fe3STobias Grosser   ///
36532837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
36632837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
36732837fe3STobias Grosser 
36832837fe3STobias Grosser   /// The GPU program we generate code for.
36932837fe3STobias Grosser   gpu_prog *Prog;
37032837fe3STobias Grosser 
37117f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
37217f01968SSiddharth Bhat   GPURuntime Runtime;
37317f01968SSiddharth Bhat 
37417f01968SSiddharth Bhat   /// The GPU Architecture to target.
37517f01968SSiddharth Bhat   GPUArch Arch;
37617f01968SSiddharth Bhat 
377472f9654STobias Grosser   /// Class to free isl_ids.
378472f9654STobias Grosser   class IslIdDeleter {
379472f9654STobias Grosser   public:
380472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
381472f9654STobias Grosser   };
382472f9654STobias Grosser 
383472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
384472f9654STobias Grosser   ///
385472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
386472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
387472f9654STobias Grosser 
388edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
389edb885cbSTobias Grosser 
39038fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
39138fc0aedSTobias Grosser   ///
39238fc0aedSTobias Grosser   /// These AST nodes can be of type:
39338fc0aedSTobias Grosser   ///
39438fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
39538fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
39613c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
3975260c041STobias Grosser   ///   - In-kernel synchronization
3985260c041STobias Grosser   ///   - In-kernel memory copy statement
39938fc0aedSTobias Grosser   ///
4001fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4011fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
40232837fe3STobias Grosser 
40313c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
40413c78e4dSTobias Grosser 
40513c78e4dSTobias Grosser   /// Create code for a data transfer statement
40613c78e4dSTobias Grosser   ///
40713c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
40813c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
40913c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
41013c78e4dSTobias Grosser                           enum DataDirection Direction);
41113c78e4dSTobias Grosser 
412edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
413edb885cbSTobias Grosser   ///
414edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
415edb885cbSTobias Grosser   ///
416f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
417f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
418f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
419f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
420f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
421f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
422edb885cbSTobias Grosser 
42379a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
42479a947c2STobias Grosser   ///
42579a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
42679a947c2STobias Grosser   ///
42779a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
42879a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
42979a947c2STobias Grosser 
430abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
431abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
432abed4969SSiddharth Bhat   /// host pointers to the device.
433abed4969SSiddharth Bhat   /// \note
434abed4969SSiddharth Bhat   /// This is to be used only with managed memory
435abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
436abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
437abed4969SSiddharth Bhat 
43879a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
43979a947c2STobias Grosser   ///
44079a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
44179a947c2STobias Grosser   ///
44279a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
44379a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
44479a947c2STobias Grosser 
445a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
446a90be207SSiddharth Bhat   /// parameters.
447a90be207SSiddharth Bhat   ///
448a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
449a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
450a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
451a90be207SSiddharth Bhat   ///                   parameter.
452a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
453a90be207SSiddharth Bhat                             int Index);
454a90be207SSiddharth Bhat 
45579a947c2STobias Grosser   /// Create kernel launch parameters.
45679a947c2STobias Grosser   ///
45779a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
45879a947c2STobias Grosser   /// @param F             The kernel function that has been created.
45957693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
46079a947c2STobias Grosser   ///
46179a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
46279a947c2STobias Grosser   ///          values that are passed to the kernel.
46357693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
46457693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
46579a947c2STobias Grosser 
466b513b491STobias Grosser   /// Create declarations for kernel variable.
467b513b491STobias Grosser   ///
468b513b491STobias Grosser   /// This includes shared memory declarations.
469b513b491STobias Grosser   ///
470b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
471b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
472b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
473b513b491STobias Grosser 
474c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
475c1c6a2a6STobias Grosser   ///
476c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
477c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
478c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
479c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
480c1c6a2a6STobias Grosser   /// as specified here.
481c1c6a2a6STobias Grosser   ///
482c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
483c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
484c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
485c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
486c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
487c1c6a2a6STobias Grosser                           Value *BlockDimZ);
488c1c6a2a6STobias Grosser 
48932837fe3STobias Grosser   /// Create GPU kernel.
49032837fe3STobias Grosser   ///
49132837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
49232837fe3STobias Grosser   ///
49332837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
49432837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
49532837fe3STobias Grosser 
49613c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
49713c78e4dSTobias Grosser   ///
49813c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
49913c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
50013c78e4dSTobias Grosser 
501aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
502aaabbbf8STobias Grosser   ///
503aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
504aaabbbf8STobias Grosser   ///
505aaabbbf8STobias Grosser   /// Example:
506aaabbbf8STobias Grosser   ///
507aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
508aaabbbf8STobias Grosser   ///     A[i + 42] += ...
509aaabbbf8STobias Grosser   ///
510aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
511aaabbbf8STobias Grosser   ///
512aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
513aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
514aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
515aaabbbf8STobias Grosser 
51600bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
51700bb5a99STobias Grosser   ///
51800bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
51900bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
52000bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
52100bb5a99STobias Grosser 
52232837fe3STobias Grosser   /// Create kernel function.
52332837fe3STobias Grosser   ///
52432837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
52532837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
52632837fe3STobias Grosser   /// start block of this newly created function.
52732837fe3STobias Grosser   ///
52832837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
529edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
530f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
531f291c8d5SSiddharth Bhat   ///                         kernel.
532edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
533f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
534f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
53532837fe3STobias Grosser 
53632837fe3STobias Grosser   /// Create the declaration of a kernel function.
53732837fe3STobias Grosser   ///
53832837fe3STobias Grosser   /// The kernel function takes as arguments:
53932837fe3STobias Grosser   ///
54032837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
541f6044bd0STobias Grosser   ///   - Host iterators
542c84a1995STobias Grosser   ///   - Parameters
54332837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
54432837fe3STobias Grosser   ///
54532837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
546edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
547edb885cbSTobias Grosser   ///
54832837fe3STobias Grosser   /// @returns The newly declared function.
549edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
550edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
55132837fe3STobias Grosser 
552472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
553472f9654STobias Grosser   ///
554472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
555472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
556472f9654STobias Grosser 
5572f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5582f3073b5SPhilipp Schaad   ///
5592f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5602f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5612f3073b5SPhilipp Schaad 
562f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
563f291c8d5SSiddharth Bhat   ///
564f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
565f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
566f291c8d5SSiddharth Bhat   ///
567f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
568f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
569f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
570f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
571f291c8d5SSiddharth Bhat   ///
572f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
573f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
574f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
575f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
576f291c8d5SSiddharth Bhat   ///
577f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
578f291c8d5SSiddharth Bhat   ///                         this kernel.
579f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
580f291c8d5SSiddharth Bhat 
581b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
582b513b491STobias Grosser   ///
583b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
584b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
585b513b491STobias Grosser 
586edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
587edb885cbSTobias Grosser   ///
588edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
589edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
590edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
591edb885cbSTobias Grosser 
5925260c041STobias Grosser   /// Create an in-kernel synchronization call.
5935260c041STobias Grosser   void createKernelSync();
5945260c041STobias Grosser 
59574dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
59674dc3cb4STobias Grosser   ///
59774dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
59874dc3cb4STobias Grosser   std::string createKernelASM();
59974dc3cb4STobias Grosser 
60074dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
60174dc3cb4STobias Grosser   ///
60274dc3cb4STobias Grosser   /// @param F The function to remove references to.
60374dc3cb4STobias Grosser   void clearDominators(Function *F);
60474dc3cb4STobias Grosser 
60574dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
60674dc3cb4STobias Grosser   ///
60774dc3cb4STobias Grosser   /// @param F The function to remove references to.
60874dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
60974dc3cb4STobias Grosser 
61074dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
61174dc3cb4STobias Grosser   ///
61274dc3cb4STobias Grosser   /// @param F The function to remove references to.
61374dc3cb4STobias Grosser   void clearLoops(Function *F);
61474dc3cb4STobias Grosser 
6158fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6168fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6178fc6cdfbSTobias Grosser 
6188fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6198fc6cdfbSTobias Grosser   void addCUDALibDevice();
6208fc6cdfbSTobias Grosser 
62132837fe3STobias Grosser   /// Finalize the generation of the kernel function.
62232837fe3STobias Grosser   ///
62332837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
62432837fe3STobias Grosser   /// dump its IR to stderr.
62557793596STobias Grosser   ///
62657793596STobias Grosser   /// @returns The Assembly string of the kernel.
62757793596STobias Grosser   std::string finalizeKernelFunction();
628fa7b0802STobias Grosser 
62951dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
63051dfc275STobias Grosser   ///
63151dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
632a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
63351dfc275STobias Grosser   /// the kernel terminates.
63451dfc275STobias Grosser   ///
63551dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
63651dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
63751dfc275STobias Grosser 
6387287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
639fa7b0802STobias Grosser   void allocateDeviceArrays();
640fa7b0802STobias Grosser 
6417287aeddSTobias Grosser   /// Free all allocated device arrays.
6427287aeddSTobias Grosser   void freeDeviceArrays();
6437287aeddSTobias Grosser 
644fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
645fa7b0802STobias Grosser   ///
646fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
647fa7b0802STobias Grosser   Value *createCallInitContext();
648fa7b0802STobias Grosser 
64979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
65079a947c2STobias Grosser   ///
65179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
65279a947c2STobias Grosser   ///
65379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
65479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
65579a947c2STobias Grosser 
656fa7b0802STobias Grosser   /// Create a call to free the GPU context.
657fa7b0802STobias Grosser   ///
658fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
659fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
660fa7b0802STobias Grosser 
6617287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6627287aeddSTobias Grosser   ///
6637287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6647287aeddSTobias Grosser   ///
6657287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
666fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6677287aeddSTobias Grosser 
6687287aeddSTobias Grosser   /// Create a call to free a device array.
6697287aeddSTobias Grosser   ///
6707287aeddSTobias Grosser   /// @param Array The device array to free.
6717287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
67213c78e4dSTobias Grosser 
67313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
67413c78e4dSTobias Grosser   ///
67513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
67613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
67713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
67813c78e4dSTobias Grosser                                       Value *Size);
67913c78e4dSTobias Grosser 
68013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
68113c78e4dSTobias Grosser   ///
68213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
68313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
68413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
68513c78e4dSTobias Grosser                                       Value *Size);
68657793596STobias Grosser 
687abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
688abed4969SSiddharth Bhat   /// \note
689abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
690abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
691abed4969SSiddharth Bhat 
69257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
69357793596STobias Grosser   ///
69457793596STobias Grosser   /// @param Buffer The string describing the kernel.
69557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
69657793596STobias Grosser   ///
69757793596STobias Grosser   /// @returns A pointer to a kernel object
69857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
69957793596STobias Grosser 
70057793596STobias Grosser   /// Create a call to free a GPU kernel.
70157793596STobias Grosser   ///
70257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
70357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
70479a947c2STobias Grosser 
70579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
70679a947c2STobias Grosser   ///
70779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
70879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
70979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
71079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
71179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
71279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
713a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
71479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
71579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
71679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
71779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
71879a947c2STobias Grosser                               Value *Parameters);
7191fb9b64dSTobias Grosser };
7201fb9b64dSTobias Grosser 
72179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7221abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7231abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
72479f13b9aSSingapuram Sanjay Srivallabh }
72579f13b9aSSingapuram Sanjay Srivallabh 
726fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
727750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
728750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
729750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
730750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
731750160e2STobias Grosser 
732fa7b0802STobias Grosser   GPUContext = createCallInitContext();
733abed4969SSiddharth Bhat 
734abed4969SSiddharth Bhat   if (!ManagedMemory)
735fa7b0802STobias Grosser     allocateDeviceArrays();
736fa7b0802STobias Grosser }
737fa7b0802STobias Grosser 
738fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
739abed4969SSiddharth Bhat   if (!ManagedMemory)
7407287aeddSTobias Grosser     freeDeviceArrays();
741abed4969SSiddharth Bhat 
742fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
743fa7b0802STobias Grosser   IslNodeBuilder::finalize();
744fa7b0802STobias Grosser }
745fa7b0802STobias Grosser 
746fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
747abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
748abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
749fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
750fa7b0802STobias Grosser 
751fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
752fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
75313c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7547287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7557287aeddSTobias Grosser     DevArrayName.append(Array->name);
756fa7b0802STobias Grosser 
75713c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
758aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
759aaabbbf8STobias Grosser     if (Offset)
760aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
761aaabbbf8STobias Grosser           ArraySize,
762aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
763aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7647287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7657287aeddSTobias Grosser     DevArray->setName(DevArrayName);
76613c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
767fa7b0802STobias Grosser   }
768fa7b0802STobias Grosser 
769fa7b0802STobias Grosser   isl_ast_build_free(Build);
770fa7b0802STobias Grosser }
771fa7b0802STobias Grosser 
772c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
773c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
774c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
775c1c6a2a6STobias Grosser 
776c1c6a2a6STobias Grosser   for (auto &F : *M) {
777c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
778c1c6a2a6STobias Grosser       continue;
779c1c6a2a6STobias Grosser 
780c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
781c1c6a2a6STobias Grosser 
782c1c6a2a6STobias Grosser     Metadata *Elements[] = {
783c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
784c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
785c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
786c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
787c1c6a2a6STobias Grosser     };
788c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
789c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
790c1c6a2a6STobias Grosser   }
791c1c6a2a6STobias Grosser }
792c1c6a2a6STobias Grosser 
7937287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
794abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
79513c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
79613c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
7977287aeddSTobias Grosser }
7987287aeddSTobias Grosser 
79957793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
80057793596STobias Grosser   const char *Name = "polly_getKernel";
80157793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
80257793596STobias Grosser   Function *F = M->getFunction(Name);
80357793596STobias Grosser 
80457793596STobias Grosser   // If F is not available, declare it.
80557793596STobias Grosser   if (!F) {
80657793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
80757793596STobias Grosser     std::vector<Type *> Args;
80857793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
80957793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
81057793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
81157793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
81257793596STobias Grosser   }
81357793596STobias Grosser 
81457793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
81557793596STobias Grosser }
81657793596STobias Grosser 
81779a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
81879a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
81979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
82079a947c2STobias Grosser   Function *F = M->getFunction(Name);
82179a947c2STobias Grosser 
82279a947c2STobias Grosser   // If F is not available, declare it.
82379a947c2STobias Grosser   if (!F) {
82479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
82579a947c2STobias Grosser     std::vector<Type *> Args;
82679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
82879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
82979a947c2STobias Grosser   }
83079a947c2STobias Grosser 
83179a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
83279a947c2STobias Grosser }
83379a947c2STobias Grosser 
83479a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
83579a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
83679a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
83779a947c2STobias Grosser                                             Value *Parameters) {
83879a947c2STobias Grosser   const char *Name = "polly_launchKernel";
83979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
84079a947c2STobias Grosser   Function *F = M->getFunction(Name);
84179a947c2STobias Grosser 
84279a947c2STobias Grosser   // If F is not available, declare it.
84379a947c2STobias Grosser   if (!F) {
84479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
84579a947c2STobias Grosser     std::vector<Type *> Args;
84679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
84779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
84879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
84979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
85279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
85479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
85579a947c2STobias Grosser   }
85679a947c2STobias Grosser 
857ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
85879a947c2STobias Grosser                          BlockDimZ, Parameters});
85979a947c2STobias Grosser }
86079a947c2STobias Grosser 
86157793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
86257793596STobias Grosser   const char *Name = "polly_freeKernel";
86357793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
86457793596STobias Grosser   Function *F = M->getFunction(Name);
86557793596STobias Grosser 
86657793596STobias Grosser   // If F is not available, declare it.
86757793596STobias Grosser   if (!F) {
86857793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
86957793596STobias Grosser     std::vector<Type *> Args;
87057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87157793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
87257793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
87357793596STobias Grosser   }
87457793596STobias Grosser 
87557793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
87657793596STobias Grosser }
87757793596STobias Grosser 
8787287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
879abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
880abed4969SSiddharth Bhat                            "for device");
8817287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8827287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8837287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8847287aeddSTobias Grosser 
8857287aeddSTobias Grosser   // If F is not available, declare it.
8867287aeddSTobias Grosser   if (!F) {
8877287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8887287aeddSTobias Grosser     std::vector<Type *> Args;
8897287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8907287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8917287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8927287aeddSTobias Grosser   }
8937287aeddSTobias Grosser 
8947287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
8957287aeddSTobias Grosser }
8967287aeddSTobias Grosser 
897fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
898abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
899abed4969SSiddharth Bhat                            "for device");
900fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
901fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
902fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
903fa7b0802STobias Grosser 
904fa7b0802STobias Grosser   // If F is not available, declare it.
905fa7b0802STobias Grosser   if (!F) {
906fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
907fa7b0802STobias Grosser     std::vector<Type *> Args;
908fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
909fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
910fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
911fa7b0802STobias Grosser   }
912fa7b0802STobias Grosser 
913fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
914fa7b0802STobias Grosser }
915fa7b0802STobias Grosser 
91613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
91713c78e4dSTobias Grosser                                                     Value *DeviceData,
91813c78e4dSTobias Grosser                                                     Value *Size) {
919abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
920abed4969SSiddharth Bhat                            "device and host");
92113c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
92213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
92413c78e4dSTobias Grosser 
92513c78e4dSTobias Grosser   // If F is not available, declare it.
92613c78e4dSTobias Grosser   if (!F) {
92713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
92813c78e4dSTobias Grosser     std::vector<Type *> Args;
92913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
93213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
93313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
93413c78e4dSTobias Grosser   }
93513c78e4dSTobias Grosser 
93613c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
93713c78e4dSTobias Grosser }
93813c78e4dSTobias Grosser 
93913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
94013c78e4dSTobias Grosser                                                     Value *HostData,
94113c78e4dSTobias Grosser                                                     Value *Size) {
942abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
943abed4969SSiddharth Bhat                            "device and host");
94413c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
94513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
94613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
94713c78e4dSTobias Grosser 
94813c78e4dSTobias Grosser   // If F is not available, declare it.
94913c78e4dSTobias Grosser   if (!F) {
95013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
95113c78e4dSTobias Grosser     std::vector<Type *> Args;
95213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
95413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
95513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
95613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
95713c78e4dSTobias Grosser   }
95813c78e4dSTobias Grosser 
95913c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
96013c78e4dSTobias Grosser }
96113c78e4dSTobias Grosser 
962abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
963abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
964abed4969SSiddharth Bhat                           "managed memory");
965abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
966abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
967abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
968abed4969SSiddharth Bhat 
969abed4969SSiddharth Bhat   // If F is not available, declare it.
970abed4969SSiddharth Bhat   if (!F) {
971abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
972abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
973abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
974abed4969SSiddharth Bhat   }
975abed4969SSiddharth Bhat 
976abed4969SSiddharth Bhat   Builder.CreateCall(F);
977abed4969SSiddharth Bhat }
978abed4969SSiddharth Bhat 
979fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
98017f01968SSiddharth Bhat   const char *Name;
98117f01968SSiddharth Bhat 
98217f01968SSiddharth Bhat   switch (Runtime) {
98317f01968SSiddharth Bhat   case GPURuntime::CUDA:
98417f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
98517f01968SSiddharth Bhat     break;
98617f01968SSiddharth Bhat   case GPURuntime::OpenCL:
98717f01968SSiddharth Bhat     Name = "polly_initContextCL";
98817f01968SSiddharth Bhat     break;
98917f01968SSiddharth Bhat   }
99017f01968SSiddharth Bhat 
991fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
992fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
993fa7b0802STobias Grosser 
994fa7b0802STobias Grosser   // If F is not available, declare it.
995fa7b0802STobias Grosser   if (!F) {
996fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
997fa7b0802STobias Grosser     std::vector<Type *> Args;
998fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
999fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1000fa7b0802STobias Grosser   }
1001fa7b0802STobias Grosser 
1002fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1003fa7b0802STobias Grosser }
1004fa7b0802STobias Grosser 
1005fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1006fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1007fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1008fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1009fa7b0802STobias Grosser 
1010fa7b0802STobias Grosser   // If F is not available, declare it.
1011fa7b0802STobias Grosser   if (!F) {
1012fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1013fa7b0802STobias Grosser     std::vector<Type *> Args;
1014fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1015fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1016fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1017fa7b0802STobias Grosser   }
1018fa7b0802STobias Grosser 
1019fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1020fa7b0802STobias Grosser }
1021fa7b0802STobias Grosser 
10225260c041STobias Grosser /// Check if one string is a prefix of another.
10235260c041STobias Grosser ///
10245260c041STobias Grosser /// @param String The string in which to look for the prefix.
10255260c041STobias Grosser /// @param Prefix The prefix to look for.
10265260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10275260c041STobias Grosser   return String.find(Prefix) == 0;
10285260c041STobias Grosser }
10295260c041STobias Grosser 
103013c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1031f7face4bSSiddharth Bhat   isl::ast_build Build =
1032f7face4bSSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
103313c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
103413c78e4dSTobias Grosser 
103513c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1036f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1037f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1038f7face4bSSiddharth Bhat 
1039f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1040f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
104113c78e4dSTobias Grosser 
104213c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1043f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1044f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1045f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
104613c78e4dSTobias Grosser     }
104713c78e4dSTobias Grosser 
1048f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1049b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1050b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
105113c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
105213c78e4dSTobias Grosser   }
105313c78e4dSTobias Grosser   return ArraySize;
105413c78e4dSTobias Grosser }
105513c78e4dSTobias Grosser 
1056aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1057aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1058aaabbbf8STobias Grosser     return nullptr;
1059aaabbbf8STobias Grosser 
1060ccbf4b50SSiddharth Bhat   isl::ast_build Build =
1061ccbf4b50SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
1062aaabbbf8STobias Grosser 
1063ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1064aaabbbf8STobias Grosser 
1065ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1066aaabbbf8STobias Grosser 
1067ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1068ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1069aaabbbf8STobias Grosser 
1070ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1071aaabbbf8STobias Grosser     return nullptr;
1072aaabbbf8STobias Grosser   }
1073aaabbbf8STobias Grosser 
1074ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1075aaabbbf8STobias Grosser 
1076ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1077aaabbbf8STobias Grosser     if (i > 0) {
1078ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1079ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1080ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1081ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1082aaabbbf8STobias Grosser     }
1083ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1084ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1085ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1086aaabbbf8STobias Grosser   }
1087aaabbbf8STobias Grosser 
1088ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1089aaabbbf8STobias Grosser }
1090aaabbbf8STobias Grosser 
1091abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1092abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1093abed4969SSiddharth Bhat 
1094abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1095abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1096abed4969SSiddharth Bhat                           "with managed memory");
1097abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1098abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1099abed4969SSiddharth Bhat     return it->second;
1100abed4969SSiddharth Bhat   } else {
1101abed4969SSiddharth Bhat     Value *HostPtr;
1102abed4969SSiddharth Bhat 
1103abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1104abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1105abed4969SSiddharth Bhat     else
1106abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1107*edf9581eSSiddharth Bhat     HostPtr = getLatestValue(HostPtr);
1108abed4969SSiddharth Bhat 
1109abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1110abed4969SSiddharth Bhat     if (Offset) {
1111abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1112abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1113abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1114abed4969SSiddharth Bhat     }
1115abed4969SSiddharth Bhat 
1116abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1117abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1118abed4969SSiddharth Bhat     return HostPtr;
1119abed4969SSiddharth Bhat   }
1120abed4969SSiddharth Bhat }
1121abed4969SSiddharth Bhat 
112213c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
112313c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1124abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
112513c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
112613c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
112713c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
112813c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
112913c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
113013c78e4dSTobias Grosser 
113113c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1132aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
113313c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
113413c78e4dSTobias Grosser 
1135b06ff457STobias Grosser   Value *HostPtr;
1136b06ff457STobias Grosser 
1137b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1138b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1139b06ff457STobias Grosser   else
1140b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1141*edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
114213c78e4dSTobias Grosser 
1143aaabbbf8STobias Grosser   if (Offset) {
1144aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1145aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1146aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1147aaabbbf8STobias Grosser   }
1148aaabbbf8STobias Grosser 
114913c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
115013c78e4dSTobias Grosser 
1151aaabbbf8STobias Grosser   if (Offset) {
1152aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1153ff40087aSTobias Grosser         Size, Builder.CreateMul(
1154ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1155aaabbbf8STobias Grosser   }
1156aaabbbf8STobias Grosser 
115713c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
115813c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
115913c78e4dSTobias Grosser   else
116013c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
116113c78e4dSTobias Grosser 
116213c78e4dSTobias Grosser   isl_id_free(Id);
116313c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
116413c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
116513c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
116613c78e4dSTobias Grosser }
116713c78e4dSTobias Grosser 
11681fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
116932837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
117032837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
117132837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
117232837fe3STobias Grosser   isl_id_free(Id);
117332837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
117432837fe3STobias Grosser 
117532837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
117632837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
117732837fe3STobias Grosser     createKernel(UserStmt);
117832837fe3STobias Grosser     isl_ast_expr_free(Expr);
117932837fe3STobias Grosser     return;
118032837fe3STobias Grosser   }
11819e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11829e3db2b7SSiddharth Bhat     initializeAfterRTH();
11839e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11849e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11859e3db2b7SSiddharth Bhat     return;
11869e3db2b7SSiddharth Bhat   }
11879e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11889e3db2b7SSiddharth Bhat     finalize();
11899e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11909e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11919e3db2b7SSiddharth Bhat     return;
11929e3db2b7SSiddharth Bhat   }
119313c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1194abed4969SSiddharth Bhat     if (!ManagedMemory)
119513c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1196abed4969SSiddharth Bhat     else
1197abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1198abed4969SSiddharth Bhat 
119932837fe3STobias Grosser     isl_ast_expr_free(Expr);
120013c78e4dSTobias Grosser     return;
120113c78e4dSTobias Grosser   }
120213c78e4dSTobias Grosser 
120313c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1204abed4969SSiddharth Bhat     if (!ManagedMemory) {
120513c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1206abed4969SSiddharth Bhat     } else {
1207abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1208abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1209abed4969SSiddharth Bhat     }
121013c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
121138fc0aedSTobias Grosser     return;
121238fc0aedSTobias Grosser   }
121338fc0aedSTobias Grosser 
12145260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12155260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12165260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12175260c041STobias Grosser   isl_id_free(Anno);
12185260c041STobias Grosser 
12195260c041STobias Grosser   switch (KernelStmt->type) {
12205260c041STobias Grosser   case ppcg_kernel_domain:
1221edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12225260c041STobias Grosser     isl_ast_node_free(UserStmt);
12235260c041STobias Grosser     return;
12245260c041STobias Grosser   case ppcg_kernel_copy:
1225b513b491STobias Grosser     createKernelCopy(KernelStmt);
12265260c041STobias Grosser     isl_ast_expr_free(Expr);
12275260c041STobias Grosser     isl_ast_node_free(UserStmt);
12285260c041STobias Grosser     return;
12295260c041STobias Grosser   case ppcg_kernel_sync:
12305260c041STobias Grosser     createKernelSync();
12315260c041STobias Grosser     isl_ast_expr_free(Expr);
12325260c041STobias Grosser     isl_ast_node_free(UserStmt);
12335260c041STobias Grosser     return;
12345260c041STobias Grosser   }
12355260c041STobias Grosser 
12365260c041STobias Grosser   isl_ast_expr_free(Expr);
12375260c041STobias Grosser   isl_ast_node_free(UserStmt);
12385260c041STobias Grosser   return;
12395260c041STobias Grosser }
1240b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1241b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1242b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1243b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1244b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1245b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1246b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1247b513b491STobias Grosser 
1248b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1249b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1250b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1251b513b491STobias Grosser   } else {
1252b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1253b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1254b513b491STobias Grosser   }
1255b513b491STobias Grosser }
12565260c041STobias Grosser 
1257edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1258edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1259edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1260edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1261edb885cbSTobias Grosser 
1262edb885cbSTobias Grosser   LoopToScevMapT LTS;
1263edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1264edb885cbSTobias Grosser 
1265edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1266edb885cbSTobias Grosser 
1267edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1268edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1269edb885cbSTobias Grosser   else
1270a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1271edb885cbSTobias Grosser }
1272edb885cbSTobias Grosser 
12735260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12745260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12752f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
127617f01968SSiddharth Bhat 
127717f01968SSiddharth Bhat   Function *Sync;
127817f01968SSiddharth Bhat 
127917f01968SSiddharth Bhat   switch (Arch) {
12802f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12812f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12822f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12832f3073b5SPhilipp Schaad 
12842f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12852f3073b5SPhilipp Schaad     if (!Sync) {
12862f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
12872f3073b5SPhilipp Schaad       std::vector<Type *> Args;
12882f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
12892f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
12902f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
12912f3073b5SPhilipp Schaad     }
12922f3073b5SPhilipp Schaad     break;
129317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
129417f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
129517f01968SSiddharth Bhat     break;
129617f01968SSiddharth Bhat   }
129717f01968SSiddharth Bhat 
12985260c041STobias Grosser   Builder.CreateCall(Sync, {});
12995260c041STobias Grosser }
13005260c041STobias Grosser 
1301edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1302edb885cbSTobias Grosser ///
1303edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1304edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1305edb885cbSTobias Grosser ///
1306edb885cbSTobias Grosser /// @param Node The node to collect references for.
1307edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1308edb885cbSTobias Grosser ///
1309edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1310edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1311edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1312edb885cbSTobias Grosser     return isl_bool_true;
1313edb885cbSTobias Grosser 
1314edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1315edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1316edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1317edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1318edb885cbSTobias Grosser   isl_id_free(Id);
1319edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1320edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1321edb885cbSTobias Grosser 
1322edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1323edb885cbSTobias Grosser     return isl_bool_true;
1324edb885cbSTobias Grosser 
1325edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1326edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1327edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1328edb885cbSTobias Grosser   isl_id_free(Id);
1329edb885cbSTobias Grosser 
133000bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1331edb885cbSTobias Grosser 
1332edb885cbSTobias Grosser   return isl_bool_true;
1333edb885cbSTobias Grosser }
1334edb885cbSTobias Grosser 
13358fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13368fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13378fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13388fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13398fc6cdfbSTobias Grosser 
13408fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13418fc6cdfbSTobias Grosser ///
13428fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13438fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13448fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13458fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13468fc6cdfbSTobias Grosser 
13478fc6cdfbSTobias Grosser   return "";
13488fc6cdfbSTobias Grosser }
13498fc6cdfbSTobias Grosser 
1350f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13518fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1352f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1353f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
135454491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
135554491db6STobias Grosser   // "llvm.copysign".
135654491db6STobias Grosser   const StringRef Name = F->getName();
13578fc6cdfbSTobias Grosser 
13588fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13598fc6cdfbSTobias Grosser     return true;
13608fc6cdfbSTobias Grosser 
136154491db6STobias Grosser   return F->isIntrinsic() &&
136254491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
136354491db6STobias Grosser           Name.startswith("llvm.copysign"));
1364f291c8d5SSiddharth Bhat }
1365f291c8d5SSiddharth Bhat 
1366f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1367f291c8d5SSiddharth Bhat ///
1368f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1369f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1370f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1371f291c8d5SSiddharth Bhat /// `Function`s.
1372f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1373f291c8d5SSiddharth Bhat 
1374f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1375f291c8d5SSiddharth Bhat static SetVector<Function *>
13768fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13778fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1378f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1379f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1380f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1381f291c8d5SSiddharth Bhat     if (F) {
13828fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
13838fc6cdfbSTobias Grosser              "Code should have bailed out by "
1384f291c8d5SSiddharth Bhat              "this point if an invalid function "
1385f291c8d5SSiddharth Bhat              "were present in a kernel.");
1386f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1387f291c8d5SSiddharth Bhat     }
1388f291c8d5SSiddharth Bhat   }
1389f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1390f291c8d5SSiddharth Bhat }
1391f291c8d5SSiddharth Bhat 
1392f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1393f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1394edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1395edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1396edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1397edb885cbSTobias Grosser   SubtreeReferences References = {
1398edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1399edb885cbSTobias Grosser 
1400edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1401edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1402edb885cbSTobias Grosser 
1403edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1404edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1405edb885cbSTobias Grosser 
1406edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1407edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1408edb885cbSTobias Grosser 
1409edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1410d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1411edb885cbSTobias Grosser 
1412edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1413edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1414edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1415edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1416edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1417edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1418edb885cbSTobias Grosser     isl_id_free(Id);
1419edb885cbSTobias Grosser   }
1420edb885cbSTobias Grosser   isl_space_free(Space);
1421edb885cbSTobias Grosser 
1422edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1423edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1424edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1425edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1426edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1427edb885cbSTobias Grosser     isl_id_free(Id);
1428edb885cbSTobias Grosser   }
1429edb885cbSTobias Grosser 
1430f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1431f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1432f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1433f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1434f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1435f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1436f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1437f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1438f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14398fc6cdfbSTobias Grosser 
14408fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14418fc6cdfbSTobias Grosser 
1442f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14438fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1444f291c8d5SSiddharth Bhat 
1445a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1446a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1447a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1448a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1449a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1450a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1451a1b2086aSSiddharth Bhat     else
1452a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1453a1b2086aSSiddharth Bhat   }
1454a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1455edb885cbSTobias Grosser }
1456edb885cbSTobias Grosser 
145774dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
145874dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
145974dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
146074dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
146174dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
146274dc3cb4STobias Grosser 
146374dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
146474dc3cb4STobias Grosser     DT.eraseNode(BB);
146574dc3cb4STobias Grosser }
146674dc3cb4STobias Grosser 
146774dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
146874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
146974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
147074dc3cb4STobias Grosser     if (L)
147174dc3cb4STobias Grosser       SE.forgetLoop(L);
147274dc3cb4STobias Grosser   }
147374dc3cb4STobias Grosser }
147474dc3cb4STobias Grosser 
147574dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
147674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
147774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
147874dc3cb4STobias Grosser     if (L)
147974dc3cb4STobias Grosser       SE.forgetLoop(L);
148074dc3cb4STobias Grosser     LI.removeBlock(&BB);
148174dc3cb4STobias Grosser   }
148274dc3cb4STobias Grosser }
148374dc3cb4STobias Grosser 
148479a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
148579a947c2STobias Grosser   std::vector<Value *> Sizes;
14864d5820d1SSiddharth Bhat   isl::ast_build Context =
14874d5820d1SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
148879a947c2STobias Grosser 
14894d5820d1SSiddharth Bhat   isl::multi_pw_aff GridSizePwAffs =
14904d5820d1SSiddharth Bhat       isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size));
149179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
14924d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
14934d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
14944d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
149579a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
149679a947c2STobias Grosser     Sizes.push_back(Res);
149779a947c2STobias Grosser   }
149879a947c2STobias Grosser 
149979a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
150079a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
150179a947c2STobias Grosser 
150279a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
150379a947c2STobias Grosser }
150479a947c2STobias Grosser 
150579a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
150679a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
150779a947c2STobias Grosser   std::vector<Value *> Sizes;
150879a947c2STobias Grosser 
150979a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
151079a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
151179a947c2STobias Grosser     Sizes.push_back(Res);
151279a947c2STobias Grosser   }
151379a947c2STobias Grosser 
151479a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
151579a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
151679a947c2STobias Grosser 
151779a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
151879a947c2STobias Grosser }
151979a947c2STobias Grosser 
1520a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1521a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1522a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1523a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1524a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1525a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1526a90be207SSiddharth Bhat }
1527a90be207SSiddharth Bhat 
152857693272STobias Grosser Value *
152957693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
153057693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1531a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1532a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1533a90be207SSiddharth Bhat 
1534a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
153579a947c2STobias Grosser 
153679a947c2STobias Grosser   BasicBlock *EntryBlock =
153779a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
153867726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
153979a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
154067726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
154167726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
154279a947c2STobias Grosser 
154379a947c2STobias Grosser   int Index = 0;
154479a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
154579a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
154679a947c2STobias Grosser       continue;
154779a947c2STobias Grosser 
154879a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1549206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
155079a947c2STobias Grosser 
1551a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1552a90be207SSiddharth Bhat 
1553abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1554abed4969SSiddharth Bhat     if (ManagedMemory) {
1555abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1556abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1557abed4969SSiddharth Bhat     } else {
1558abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
155979a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1560abed4969SSiddharth Bhat     }
1561abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1562abed4969SSiddharth Bhat                                   "initialized");
1563aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1564aaabbbf8STobias Grosser 
1565aaabbbf8STobias Grosser     if (Offset) {
1566aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1567aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1568aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1569aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1570aaabbbf8STobias Grosser     }
1571fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1572fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1573aaabbbf8STobias Grosser 
1574fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1575abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1576abed4969SSiddharth Bhat       if (ManagedMemory)
1577abed4969SSiddharth Bhat         ValPtr = DevArray;
1578abed4969SSiddharth Bhat       else
1579abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1580abed4969SSiddharth Bhat 
1581abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1582abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1583fe74a7a1STobias Grosser       Value *ValPtrCast =
1584fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1585fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1586fe74a7a1STobias Grosser     } else {
158767726b32STobias Grosser       Instruction *Param =
158867726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
158967726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
159079a947c2STobias Grosser                          EntryBlock->getTerminator());
159179a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
159279a947c2STobias Grosser       Value *ParamTyped =
159379a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
159479a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1595fe74a7a1STobias Grosser     }
159679a947c2STobias Grosser     Index++;
159779a947c2STobias Grosser   }
159879a947c2STobias Grosser 
1599a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1600a490147cSTobias Grosser 
1601a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1602a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1603a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1604a490147cSTobias Grosser     isl_id_free(Id);
1605a90be207SSiddharth Bhat 
1606a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1607a90be207SSiddharth Bhat 
160867726b32STobias Grosser     Instruction *Param =
160967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
161067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1611a490147cSTobias Grosser                        EntryBlock->getTerminator());
1612a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1613a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1614a490147cSTobias Grosser     Index++;
1615a490147cSTobias Grosser   }
1616a490147cSTobias Grosser 
1617d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1618d8b94bcaSTobias Grosser 
1619d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1620d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1621d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1622a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1623a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1624d8b94bcaSTobias Grosser     isl_id_free(Id);
1625a90be207SSiddharth Bhat 
1626a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1627a90be207SSiddharth Bhat 
162867726b32STobias Grosser     Instruction *Param =
162967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
163067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1631d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1632d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1633a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1634d8b94bcaSTobias Grosser     Index++;
1635d8b94bcaSTobias Grosser   }
1636d8b94bcaSTobias Grosser 
163757693272STobias Grosser   for (auto Val : SubtreeValues) {
1638a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1639a90be207SSiddharth Bhat 
164067726b32STobias Grosser     Instruction *Param =
164167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
164267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
164357693272STobias Grosser                        EntryBlock->getTerminator());
164457693272STobias Grosser     Builder.CreateStore(Val, Param);
1645a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1646a90be207SSiddharth Bhat     Index++;
1647a90be207SSiddharth Bhat   }
1648a90be207SSiddharth Bhat 
1649a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1650a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1651a90be207SSiddharth Bhat     Instruction *Param =
1652a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1653a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1654a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1655a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1656a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
165757693272STobias Grosser     Index++;
165857693272STobias Grosser   }
165957693272STobias Grosser 
166079a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
166179a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
166279a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
166379a947c2STobias Grosser }
166479a947c2STobias Grosser 
1665f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1666f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1667f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1668f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1669f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1670f291c8d5SSiddharth Bhat     if (!Clone)
1671f291c8d5SSiddharth Bhat       Clone =
1672f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1673f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1674f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1675f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1676f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1677f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1678f291c8d5SSiddharth Bhat   }
1679f291c8d5SSiddharth Bhat }
168032837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
168132837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
168232837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
168332837fe3STobias Grosser   isl_id_free(Id);
168432837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
168532837fe3STobias Grosser 
1686bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1687bc653f20STobias Grosser     DeepestParallel =
1688bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1689bc653f20STobias Grosser   else
1690bc653f20STobias Grosser     DeepestSequential =
1691bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1692bc653f20STobias Grosser 
1693c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1694c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1695c1c6a2a6STobias Grosser 
1696f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1697f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1698f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1699edb885cbSTobias Grosser 
170032837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
170132837fe3STobias Grosser 
170232837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1703472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1704edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1705587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1706b06ff457STobias Grosser   ScalarMap.clear();
170732837fe3STobias Grosser 
1708edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1709edb885cbSTobias Grosser 
1710edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1711edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1712edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1713edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1714edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1715edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1716edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1717edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1718edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1719edb885cbSTobias Grosser     SubtreeValues.insert(V);
1720edb885cbSTobias Grosser   }
1721edb885cbSTobias Grosser 
1722f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1723f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
172432837fe3STobias Grosser 
172559ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
172659ab0705STobias Grosser 
172751dfc275STobias Grosser   finalizeKernelArguments(Kernel);
172874dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17292f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1730c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
173174dc3cb4STobias Grosser   clearDominators(F);
173274dc3cb4STobias Grosser   clearScalarEvolution(F);
173374dc3cb4STobias Grosser   clearLoops(F);
173474dc3cb4STobias Grosser 
1735472f9654STobias Grosser   IDToValue = HostIDs;
173632837fe3STobias Grosser 
1737b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1738b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1739edb885cbSTobias Grosser   EscapeMap.clear();
1740edb885cbSTobias Grosser   IDToSAI.clear();
174174dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
174274dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17434d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
174474dc3cb4STobias Grosser   LocalArrays.clear();
1745edb885cbSTobias Grosser 
174651dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
174751dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
174857693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
174979a947c2STobias Grosser 
175079f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
175157793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
175257793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
175357793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
175479a947c2STobias Grosser 
175579a947c2STobias Grosser   Value *GridDimX, *GridDimY;
175679a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
175779a947c2STobias Grosser 
175879a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
175979a947c2STobias Grosser                          BlockDimZ, Parameters);
176057793596STobias Grosser   createCallFreeKernel(GPUKernel);
1761b513b491STobias Grosser 
1762b513b491STobias Grosser   for (auto Id : KernelIds)
1763b513b491STobias Grosser     isl_id_free(Id);
1764b513b491STobias Grosser 
1765b513b491STobias Grosser   KernelIds.clear();
176632837fe3STobias Grosser }
176732837fe3STobias Grosser 
176832837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
176932837fe3STobias Grosser ///
177032837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
177132837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1772d277fedaSSiddharth Bhat   std::string Ret = "";
177332837fe3STobias Grosser 
1774d277fedaSSiddharth Bhat   if (!is64Bit) {
1775d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
177630caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1777d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1778d277fedaSSiddharth Bhat   } else {
1779d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
178030caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1781d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1782d277fedaSSiddharth Bhat   }
178332837fe3STobias Grosser 
178432837fe3STobias Grosser   return Ret;
178532837fe3STobias Grosser }
178632837fe3STobias Grosser 
17872f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
17882f3073b5SPhilipp Schaad ///
17892f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
17902f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
17912f3073b5SPhilipp Schaad   std::string Ret = "";
17922f3073b5SPhilipp Schaad 
17932f3073b5SPhilipp Schaad   if (!is64Bit) {
17942f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
179530caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17962f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17972f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17982f3073b5SPhilipp Schaad   } else {
17992f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
180030caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
18012f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
18022f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
18032f3073b5SPhilipp Schaad   }
18042f3073b5SPhilipp Schaad 
18052f3073b5SPhilipp Schaad   return Ret;
18062f3073b5SPhilipp Schaad }
18072f3073b5SPhilipp Schaad 
1808edb885cbSTobias Grosser Function *
1809edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1810edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
181132837fe3STobias Grosser   std::vector<Type *> Args;
181279f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
181332837fe3STobias Grosser 
18142f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18152f3073b5SPhilipp Schaad 
181632837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
181732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
181832837fe3STobias Grosser       continue;
181932837fe3STobias Grosser 
1820fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1821fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1822206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1823fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18242f3073b5SPhilipp Schaad       MemoryType.push_back(
18252f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1826fe74a7a1STobias Grosser     } else {
1827d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1828d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18292f3073b5SPhilipp Schaad       MemoryType.push_back(
18302f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
183132837fe3STobias Grosser     }
1832fe74a7a1STobias Grosser   }
183332837fe3STobias Grosser 
1834f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1835f6044bd0STobias Grosser 
18362f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1837f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18382f3073b5SPhilipp Schaad     MemoryType.push_back(
18392f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18402f3073b5SPhilipp Schaad   }
1841f6044bd0STobias Grosser 
1842c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1843c84a1995STobias Grosser 
1844cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1845cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1846cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1847cf66ef26STobias Grosser     isl_id_free(Id);
1848cf66ef26STobias Grosser     Args.push_back(Val->getType());
18492f3073b5SPhilipp Schaad     MemoryType.push_back(
18502f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1851cf66ef26STobias Grosser   }
1852c84a1995STobias Grosser 
18532f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1854edb885cbSTobias Grosser     Args.push_back(V->getType());
18552f3073b5SPhilipp Schaad     MemoryType.push_back(
18562f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18572f3073b5SPhilipp Schaad   }
1858edb885cbSTobias Grosser 
185932837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
186032837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
186132837fe3STobias Grosser                               GPUModule.get());
186217f01968SSiddharth Bhat 
18632f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18642f3073b5SPhilipp Schaad 
18652f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18662f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18672f3073b5SPhilipp Schaad   }
18682f3073b5SPhilipp Schaad 
18692f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18702f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18712f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18722f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18732f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18742f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
18752f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18762f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
18772f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18782f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
18792f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18802f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
18812f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18822f3073b5SPhilipp Schaad   }
18832f3073b5SPhilipp Schaad 
188417f01968SSiddharth Bhat   switch (Arch) {
188517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
188632837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
188717f01968SSiddharth Bhat     break;
18882f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
18892f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
18902f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
18912f3073b5SPhilipp Schaad     break;
189217f01968SSiddharth Bhat   }
189332837fe3STobias Grosser 
189432837fe3STobias Grosser   auto Arg = FN->arg_begin();
189532837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
189632837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
189732837fe3STobias Grosser       continue;
189832837fe3STobias Grosser 
1899edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1900edb885cbSTobias Grosser 
1901edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1902206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1903206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1904edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1905edb885cbSTobias Grosser     Value *Val = &*Arg;
1906edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1907edb885cbSTobias Grosser     isl_ast_build *Build =
1908edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1909f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1910edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1911edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19129e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1913edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1914edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1915edb885cbSTobias Grosser     }
1916edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19174d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
191874dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1919edb885cbSTobias Grosser 
1920edb885cbSTobias Grosser     isl_ast_build_free(Build);
1921b513b491STobias Grosser     KernelIds.push_back(Id);
1922edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
192332837fe3STobias Grosser     Arg++;
192432837fe3STobias Grosser   }
192532837fe3STobias Grosser 
1926f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1927f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1928f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1929f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1930f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1931f6044bd0STobias Grosser     Arg++;
1932f6044bd0STobias Grosser   }
1933f6044bd0STobias Grosser 
1934c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1935c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1936c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
193712453403STobias Grosser     Value *Val = IDToValue[Id];
193812453403STobias Grosser     ValueMap[Val] = &*Arg;
1939c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1940c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1941c84a1995STobias Grosser     Arg++;
1942c84a1995STobias Grosser   }
1943c84a1995STobias Grosser 
1944edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1945edb885cbSTobias Grosser     Arg->setName(V->getName());
1946edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1947edb885cbSTobias Grosser     Arg++;
1948edb885cbSTobias Grosser   }
1949edb885cbSTobias Grosser 
195032837fe3STobias Grosser   return FN;
195132837fe3STobias Grosser }
195232837fe3STobias Grosser 
1953472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
195417f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
195517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1956472f9654STobias Grosser 
195717f01968SSiddharth Bhat   switch (Arch) {
19582f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19592f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19602f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
196117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
196217f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
196317f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
196417f01968SSiddharth Bhat 
196517f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
196617f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
196717f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
196817f01968SSiddharth Bhat     break;
196917f01968SSiddharth Bhat   }
1970472f9654STobias Grosser 
1971472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1972472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1973472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1974472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1975472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1976472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1977472f9654STobias Grosser     IDToValue[Id] = Val;
1978472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1979472f9654STobias Grosser   };
1980472f9654STobias Grosser 
1981472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1982472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1983472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1984472f9654STobias Grosser   }
1985472f9654STobias Grosser 
1986472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1987472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1988472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1989472f9654STobias Grosser   }
1990472f9654STobias Grosser }
1991472f9654STobias Grosser 
19922f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
19932f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
19942f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
19952f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
19962f3073b5SPhilipp Schaad 
19972f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
19982f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
19992f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
20002f3073b5SPhilipp Schaad 
20012f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
20022f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20032f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20042f3073b5SPhilipp Schaad 
20052f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20062f3073b5SPhilipp Schaad     if (!FN) {
20072f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20082f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20092f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20102f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20112f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20122f3073b5SPhilipp Schaad     }
20132f3073b5SPhilipp Schaad 
20142f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20152f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20162f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20172f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20182f3073b5SPhilipp Schaad   };
20192f3073b5SPhilipp Schaad 
20202f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20212f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20222f3073b5SPhilipp Schaad 
20232f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20242f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20252f3073b5SPhilipp Schaad }
20262f3073b5SPhilipp Schaad 
202700bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
202800bb5a99STobias Grosser   auto Arg = FN->arg_begin();
202900bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
203000bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
203100bb5a99STobias Grosser       continue;
203200bb5a99STobias Grosser 
203300bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2034206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2035206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
203600bb5a99STobias Grosser     isl_id_free(Id);
203700bb5a99STobias Grosser 
203800bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
203900bb5a99STobias Grosser       Arg++;
204000bb5a99STobias Grosser       continue;
204100bb5a99STobias Grosser     }
204200bb5a99STobias Grosser 
2043fe74a7a1STobias Grosser     Value *Val = &*Arg;
2044fe74a7a1STobias Grosser 
2045fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
204600bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2047fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2048fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2049fe74a7a1STobias Grosser     }
2050fe74a7a1STobias Grosser 
2051fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
205200bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
205300bb5a99STobias Grosser 
205400bb5a99STobias Grosser     Arg++;
205500bb5a99STobias Grosser   }
205600bb5a99STobias Grosser }
205700bb5a99STobias Grosser 
205851dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
205951dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
206051dfc275STobias Grosser   auto Arg = FN->arg_begin();
206151dfc275STobias Grosser 
206251dfc275STobias Grosser   bool StoredScalar = false;
206351dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
206451dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
206551dfc275STobias Grosser       continue;
206651dfc275STobias Grosser 
206751dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2068206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2069206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
207051dfc275STobias Grosser     isl_id_free(Id);
207151dfc275STobias Grosser 
207251dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
207351dfc275STobias Grosser       Arg++;
207451dfc275STobias Grosser       continue;
207551dfc275STobias Grosser     }
207651dfc275STobias Grosser 
207751dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
207851dfc275STobias Grosser       Arg++;
207951dfc275STobias Grosser       continue;
208051dfc275STobias Grosser     }
208151dfc275STobias Grosser 
208251dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
208351dfc275STobias Grosser     Value *ArgPtr = &*Arg;
208451dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
208551dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
208651dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
208751dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
208851dfc275STobias Grosser     StoredScalar = true;
208951dfc275STobias Grosser 
209051dfc275STobias Grosser     Arg++;
209151dfc275STobias Grosser   }
209251dfc275STobias Grosser 
209351dfc275STobias Grosser   if (StoredScalar)
209451dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
209551dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
209651dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
209751dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
209851dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
209951dfc275STobias Grosser       BuildSuccessful = 0;
210051dfc275STobias Grosser }
210151dfc275STobias Grosser 
2102b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2103b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2104b513b491STobias Grosser 
2105b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2106b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2107b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2108206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2109b513b491STobias Grosser 
2110f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2111b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2112b513b491STobias Grosser 
2113f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2114928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2115b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2116f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2117b513b491STobias Grosser       isl_val_free(Val);
2118b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2119928d7573STobias Grosser     }
2120928d7573STobias Grosser 
2121928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2122928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2123928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2124928d7573STobias Grosser       isl_val_free(Val);
2125b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2126b513b491STobias Grosser     }
2127b513b491STobias Grosser 
2128130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2129130ca30fSTobias Grosser     Value *Allocation;
2130130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2131130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2132130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2133130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2134130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2135f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2136f919d8b3STobias Grosser 
2137130ca30fSTobias Grosser       Allocation = GlobalVar;
2138130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2139130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2140130ca30fSTobias Grosser     } else {
2141130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2142130ca30fSTobias Grosser     }
21434d5a9172STobias Grosser     SAI =
21444d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2145b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2146130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2147130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2148b513b491STobias Grosser     KernelIds.push_back(Id);
2149b513b491STobias Grosser     IDToSAI[Id] = SAI;
2150b513b491STobias Grosser   }
2151b513b491STobias Grosser }
2152b513b491STobias Grosser 
2153f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2154f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2155f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
215679f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
215732837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
215817f01968SSiddharth Bhat 
215917f01968SSiddharth Bhat   switch (Arch) {
216017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
216117f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
216232837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
216317f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
216417f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
216532837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
216617f01968SSiddharth Bhat     break;
21672f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21682f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
21692f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
21702f3073b5SPhilipp Schaad     break;
21712f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21722f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
21732f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
21742f3073b5SPhilipp Schaad     break;
217517f01968SSiddharth Bhat   }
217632837fe3STobias Grosser 
2177edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
217832837fe3STobias Grosser 
217959ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
218032837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
218132837fe3STobias Grosser 
218259ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
218359ab0705STobias Grosser 
218432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
218532837fe3STobias Grosser   Builder.CreateRetVoid();
218632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2187472f9654STobias Grosser 
2188629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2189629109b6STobias Grosser 
219000bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2191b513b491STobias Grosser   createKernelVariables(Kernel, FN);
21922f3073b5SPhilipp Schaad 
21932f3073b5SPhilipp Schaad   switch (Arch) {
21942f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2195472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
21962f3073b5SPhilipp Schaad     break;
21972f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21982f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21992f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
22002f3073b5SPhilipp Schaad     break;
22012f3073b5SPhilipp Schaad   }
220232837fe3STobias Grosser }
220332837fe3STobias Grosser 
220474dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
220517f01968SSiddharth Bhat   llvm::Triple GPUTriple;
220617f01968SSiddharth Bhat 
220717f01968SSiddharth Bhat   switch (Arch) {
220817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
220917f01968SSiddharth Bhat     switch (Runtime) {
221017f01968SSiddharth Bhat     case GPURuntime::CUDA:
221117f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
221217f01968SSiddharth Bhat       break;
221317f01968SSiddharth Bhat     case GPURuntime::OpenCL:
221417f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
221517f01968SSiddharth Bhat       break;
221617f01968SSiddharth Bhat     }
221717f01968SSiddharth Bhat     break;
22182f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22192f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22202f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22212f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22222f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22232f3073b5SPhilipp Schaad     IROstream.flush();
22242f3073b5SPhilipp Schaad     return SPIRAssembly;
222517f01968SSiddharth Bhat   }
222617f01968SSiddharth Bhat 
222774dc3cb4STobias Grosser   std::string ErrMsg;
222874dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
222974dc3cb4STobias Grosser 
223074dc3cb4STobias Grosser   if (!GPUTarget) {
223174dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
223274dc3cb4STobias Grosser     return "";
223374dc3cb4STobias Grosser   }
223474dc3cb4STobias Grosser 
223574dc3cb4STobias Grosser   TargetOptions Options;
223674dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
223717f01968SSiddharth Bhat 
223817f01968SSiddharth Bhat   std::string subtarget;
223917f01968SSiddharth Bhat 
224017f01968SSiddharth Bhat   switch (Arch) {
224117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
224217f01968SSiddharth Bhat     subtarget = CudaVersion;
224317f01968SSiddharth Bhat     break;
22442f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22452f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22462f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
224717f01968SSiddharth Bhat   }
224817f01968SSiddharth Bhat 
224917f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
225017f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
225174dc3cb4STobias Grosser 
225274dc3cb4STobias Grosser   SmallString<0> ASMString;
225374dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
225474dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
225574dc3cb4STobias Grosser 
225674dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
225774dc3cb4STobias Grosser 
225874dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
225974dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
226074dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
226174dc3cb4STobias Grosser     return "";
226274dc3cb4STobias Grosser   }
226374dc3cb4STobias Grosser 
226474dc3cb4STobias Grosser   PM.run(*GPUModule);
226574dc3cb4STobias Grosser 
226674dc3cb4STobias Grosser   return ASMStream.str();
226774dc3cb4STobias Grosser }
226874dc3cb4STobias Grosser 
22698fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
22708fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
22718fc6cdfbSTobias Grosser     if (!F.isDeclaration())
22728fc6cdfbSTobias Grosser       continue;
22738fc6cdfbSTobias Grosser 
22748fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
22758fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
22768fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
22778fc6cdfbSTobias Grosser       return true;
22788fc6cdfbSTobias Grosser     }
22798fc6cdfbSTobias Grosser   }
22808fc6cdfbSTobias Grosser 
22818fc6cdfbSTobias Grosser   return false;
22828fc6cdfbSTobias Grosser }
22838fc6cdfbSTobias Grosser 
22848fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
22858fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
22868fc6cdfbSTobias Grosser     return;
22878fc6cdfbSTobias Grosser 
22888fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
22898fc6cdfbSTobias Grosser     SMDiagnostic Error;
22908fc6cdfbSTobias Grosser 
22918fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
22928fc6cdfbSTobias Grosser     auto LibDeviceModule =
22938fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
22948fc6cdfbSTobias Grosser 
22958fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
22968fc6cdfbSTobias Grosser       BuildSuccessful = false;
22978fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
22988fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
22998fc6cdfbSTobias Grosser                          "accordingly.\n");
23008fc6cdfbSTobias Grosser       return;
23018fc6cdfbSTobias Grosser     }
23028fc6cdfbSTobias Grosser 
23038fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23048fc6cdfbSTobias Grosser 
23058fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23068fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23078fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23088fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23098fc6cdfbSTobias Grosser   }
23108fc6cdfbSTobias Grosser }
23118fc6cdfbSTobias Grosser 
231257793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
231365d7f72fSSiddharth Bhat 
23145857b701STobias Grosser   if (verifyModule(*GPUModule)) {
231565d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
231665d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2317a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2318a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
231965d7f72fSSiddharth Bhat 
232065d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
232165d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
232265d7f72fSSiddharth Bhat 
23235857b701STobias Grosser     BuildSuccessful = false;
23245857b701STobias Grosser     return "";
23255857b701STobias Grosser   }
232632837fe3STobias Grosser 
23278fc6cdfbSTobias Grosser   addCUDALibDevice();
23288fc6cdfbSTobias Grosser 
232932837fe3STobias Grosser   if (DumpKernelIR)
233032837fe3STobias Grosser     outs() << *GPUModule << "\n";
233132837fe3STobias Grosser 
23322f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23339a18d559STobias Grosser     // Optimize module.
23349a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23359a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23369a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23379a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23389a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23399a18d559STobias Grosser     OptPasses.run(*GPUModule);
23402f3073b5SPhilipp Schaad   }
23419a18d559STobias Grosser 
234274dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
234374dc3cb4STobias Grosser 
234474dc3cb4STobias Grosser   if (DumpKernelASM)
234574dc3cb4STobias Grosser     outs() << Assembly << "\n";
234674dc3cb4STobias Grosser 
234732837fe3STobias Grosser   GPUModule.release();
2348472f9654STobias Grosser   KernelIDs.clear();
234957793596STobias Grosser 
235057793596STobias Grosser   return Assembly;
235132837fe3STobias Grosser }
235232837fe3STobias Grosser 
23539dfe4e7cSTobias Grosser namespace {
23549dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
23559dfe4e7cSTobias Grosser public:
23569dfe4e7cSTobias Grosser   static char ID;
23579dfe4e7cSTobias Grosser 
235817f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
235917f01968SSiddharth Bhat 
236017f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
236117f01968SSiddharth Bhat 
2362e938517eSTobias Grosser   /// The scop that is currently processed.
2363e938517eSTobias Grosser   Scop *S;
2364e938517eSTobias Grosser 
236538fc0aedSTobias Grosser   LoopInfo *LI;
236638fc0aedSTobias Grosser   DominatorTree *DT;
236738fc0aedSTobias Grosser   ScalarEvolution *SE;
236838fc0aedSTobias Grosser   const DataLayout *DL;
236938fc0aedSTobias Grosser   RegionInfo *RI;
237038fc0aedSTobias Grosser 
23719dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
23729dfe4e7cSTobias Grosser 
2373e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2374e938517eSTobias Grosser   ///
2375e938517eSTobias Grosser   /// @returns The compilation options.
2376e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2377e938517eSTobias Grosser     auto DebugOptions =
2378e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2379e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2380e938517eSTobias Grosser 
2381e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2382e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2383e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2384e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
23858950ceadSTobias Grosser     DebugOptions->verbose = false;
2386e938517eSTobias Grosser 
2387e938517eSTobias Grosser     Options->debug = DebugOptions;
2388e938517eSTobias Grosser 
23899e3db2b7SSiddharth Bhat     Options->group_chains = false;
2390e938517eSTobias Grosser     Options->reschedule = true;
2391e938517eSTobias Grosser     Options->scale_tile_loops = false;
2392e938517eSTobias Grosser     Options->wrap = false;
2393e938517eSTobias Grosser 
2394e938517eSTobias Grosser     Options->non_negative_parameters = false;
2395e938517eSTobias Grosser     Options->ctx = nullptr;
2396e938517eSTobias Grosser     Options->sizes = nullptr;
2397e938517eSTobias Grosser 
23989e3db2b7SSiddharth Bhat     Options->tile = true;
23994eaedde5STobias Grosser     Options->tile_size = 32;
24004eaedde5STobias Grosser 
24019e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
24029e3db2b7SSiddharth Bhat 
2403130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2404b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2405b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2406e938517eSTobias Grosser 
2407e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2408e938517eSTobias Grosser     Options->openmp = false;
2409e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24109e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2411e938517eSTobias Grosser 
24129e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
24139e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
24149e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24159e3db2b7SSiddharth Bhat 
24169e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24179e3db2b7SSiddharth Bhat     Options->hybrid = false;
2418e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2419e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2420e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2421e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2422e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2423e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2424e938517eSTobias Grosser 
2425e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2426e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2427e938517eSTobias Grosser 
2428e938517eSTobias Grosser     return Options;
2429e938517eSTobias Grosser   }
2430e938517eSTobias Grosser 
2431f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2432f384594dSTobias Grosser   ///
2433f384594dSTobias Grosser   /// Instead of a normal access of the form:
2434f384594dSTobias Grosser   ///
2435f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2436f384594dSTobias Grosser   ///
2437f384594dSTobias Grosser   /// a tagged access has the form
2438f384594dSTobias Grosser   ///
2439f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2440f384594dSTobias Grosser   ///
2441f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2442f384594dSTobias Grosser   /// triggered the access.
2443f384594dSTobias Grosser   ///
2444f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2445f384594dSTobias Grosser   ///
2446f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2447f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2448f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2449f384594dSTobias Grosser 
2450f384594dSTobias Grosser     for (auto &Stmt : *S)
2451f384594dSTobias Grosser       for (auto &Acc : Stmt)
2452f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
24531515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2454f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2455f384594dSTobias Grosser 
2456f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2457f384594dSTobias Grosser           Space = isl_space_range(Space);
2458f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2459fe46c3ffSTobias Grosser           Space =
2460fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2461f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2462f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2463f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2464f384594dSTobias Grosser         }
2465f384594dSTobias Grosser 
2466f384594dSTobias Grosser     return Accesses;
2467f384594dSTobias Grosser   }
2468f384594dSTobias Grosser 
2469f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2470f384594dSTobias Grosser   ///
2471f384594dSTobias Grosser   /// @see getTaggedAccesses
2472f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2473f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2474f384594dSTobias Grosser   }
2475f384594dSTobias Grosser 
2476f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2477f384594dSTobias Grosser   ///
2478f384594dSTobias Grosser   /// @see getTaggedAccesses
2479f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2480f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2481f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2482f384594dSTobias Grosser   }
2483f384594dSTobias Grosser 
2484f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2485f384594dSTobias Grosser   ///
2486f384594dSTobias Grosser   /// @see getTaggedAccesses
2487f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2488f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2489f384594dSTobias Grosser   }
2490f384594dSTobias Grosser 
2491aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2492aef5196fSTobias Grosser   ///
2493aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2494aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2495aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2496aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2497aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2498aef5196fSTobias Grosser   /// the data format that ppcg expects.
2499aef5196fSTobias Grosser   ///
2500aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2501aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2502aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2503bd81a7eeSTobias Grosser         S->getIslCtx(),
2504bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2505aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2506aef5196fSTobias Grosser 
250725271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
250825271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2509aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2510aef5196fSTobias Grosser     }
2511aef5196fSTobias Grosser 
2512aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
251377eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2514aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2515aef5196fSTobias Grosser     }
2516aef5196fSTobias Grosser 
2517aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2518aef5196fSTobias Grosser 
2519aef5196fSTobias Grosser     return Names;
2520aef5196fSTobias Grosser   }
2521aef5196fSTobias Grosser 
2522e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2523e938517eSTobias Grosser   ///
2524f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2525f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2526f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2527f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2528e938517eSTobias Grosser   ///
2529e938517eSTobias Grosser   /// @returns A new ppcg scop.
2530e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
25319e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
25329e3db2b7SSiddharth Bhat 
2533e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2534e938517eSTobias Grosser 
2535e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2536a82f2d26SSiddharth Bhat     // enable live range reordering
2537a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2538e938517eSTobias Grosser 
2539e938517eSTobias Grosser     PPCGScop->start = 0;
2540e938517eSTobias Grosser     PPCGScop->end = 0;
2541e938517eSTobias Grosser 
2542f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2543f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
25449e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
25459e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2546f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2547f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2548e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2549f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2550f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2551f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2552f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2553e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
25549e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
25559e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
25569e3db2b7SSiddharth Bhat 
2557e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2558a82f2d26SSiddharth Bhat     PPCGScop->independence =
2559a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2560e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2561e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2562e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2563e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2564e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2565e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2566e938517eSTobias Grosser 
2567f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2568a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2569a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2570a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2571a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2572a82f2d26SSiddharth Bhat 
2573a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2574e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2575e938517eSTobias Grosser 
2576f384594dSTobias Grosser     compute_tagger(PPCGScop);
2577f384594dSTobias Grosser     compute_dependences(PPCGScop);
25789e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2579f384594dSTobias Grosser 
2580e938517eSTobias Grosser     return PPCGScop;
2581e938517eSTobias Grosser   }
2582e938517eSTobias Grosser 
2583a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
258460f63b49STobias Grosser   ///
258560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
258660f63b49STobias Grosser   ///
258760f63b49STobias Grosser   /// @returns A list of array accesses.
258860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
258960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
259060f63b49STobias Grosser 
259160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
259260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
259360f63b49STobias Grosser       Access->read = Acc->isRead();
259460f63b49STobias Grosser       Access->write = Acc->isWrite();
25951515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
259660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
259760f63b49STobias Grosser       Space = isl_space_range(Space);
259860f63b49STobias Grosser       Space = isl_space_from_range(Space);
2599fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
260060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
260160f63b49STobias Grosser       Access->tagged_access =
26021515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2603b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2604fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
260560f63b49STobias Grosser       Access->next = Accesses;
2606b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
260760f63b49STobias Grosser       Accesses = Access;
260860f63b49STobias Grosser     }
260960f63b49STobias Grosser 
261060f63b49STobias Grosser     return Accesses;
261160f63b49STobias Grosser   }
261260f63b49STobias Grosser 
261369b46751STobias Grosser   /// Collect the list of GPU statements.
261469b46751STobias Grosser   ///
261569b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
261669b46751STobias Grosser   /// as well as a list with all memory accesses.
261769b46751STobias Grosser   ///
261869b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
261969b46751STobias Grosser   ///
262069b46751STobias Grosser   /// @returns A linked-list of statements.
262169b46751STobias Grosser   gpu_stmt *getStatements() {
262269b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
262369b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
262469b46751STobias Grosser 
262569b46751STobias Grosser     int i = 0;
262669b46751STobias Grosser     for (auto &Stmt : *S) {
262769b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
262869b46751STobias Grosser 
262969b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
263069b46751STobias Grosser 
263169b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
263269b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
263360f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
263469b46751STobias Grosser       i++;
263569b46751STobias Grosser     }
263669b46751STobias Grosser 
263769b46751STobias Grosser     return Stmts;
263869b46751STobias Grosser   }
263969b46751STobias Grosser 
264060f63b49STobias Grosser   /// Derive the extent of an array.
264160f63b49STobias Grosser   ///
2642d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2643d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2644d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2645d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2646d58acf86STobias Grosser   /// subscript value for the first dimension.
264760f63b49STobias Grosser   ///
264860f63b49STobias Grosser   /// @param Array The array to derive the extent for.
264960f63b49STobias Grosser   ///
265060f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
265160f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2652d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
265360f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
265460f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2655d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
265660f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2657d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2658d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2659d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2660d58acf86STobias Grosser 
2661d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2662d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
266377eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2664d58acf86STobias Grosser     }
2665d58acf86STobias Grosser 
2666d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2667d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
266877eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2669d58acf86STobias Grosser     }
2670d58acf86STobias Grosser 
267160f63b49STobias Grosser     isl_set *AccessSet =
267277eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
267360f63b49STobias Grosser 
2674d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
267577eef90fSTobias Grosser     isl_local_space *LS =
267677eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2677d58acf86STobias Grosser 
2678d58acf86STobias Grosser     isl_pw_aff *Val =
2679d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2680d58acf86STobias Grosser 
2681d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2682d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2683d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2684d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2685d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2686d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
268777eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
268877eef90fSTobias Grosser                                        Array->getBasePtrId().release());
268977eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
269077eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2691d58acf86STobias Grosser 
269277eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2693d58acf86STobias Grosser 
2694d58acf86STobias Grosser     Extent = isl_set_intersect(
2695d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2696d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2697d58acf86STobias Grosser 
2698d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2699d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2700d58acf86STobias Grosser 
2701b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2702d58acf86STobias Grosser       isl_pw_aff *PwAff =
270377eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2704b7f68b8cSSiddharth Bhat 
2705b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2706b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2707b7f68b8cSSiddharth Bhat       if (!PwAff) {
2708b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2709b7f68b8cSSiddharth Bhat         continue;
2710b7f68b8cSSiddharth Bhat       }
2711b7f68b8cSSiddharth Bhat 
2712d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
271377eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
271477eef90fSTobias Grosser           i));
2715d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2716d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2717d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2718d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2719d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2720d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2721d58acf86STobias Grosser     }
2722d58acf86STobias Grosser 
2723d58acf86STobias Grosser     return Extent;
272460f63b49STobias Grosser   }
272560f63b49STobias Grosser 
272660f63b49STobias Grosser   /// Derive the bounds of an array.
272760f63b49STobias Grosser   ///
272860f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
272960f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
273060f63b49STobias Grosser   /// ScopArrayInfo.
273160f63b49STobias Grosser   ///
273260f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
273360f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
273460f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
27359e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
27369e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
27379e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
27389e3db2b7SSiddharth Bhat 
27399e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
27409e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
27419e3db2b7SSiddharth Bhat 
274260f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
274302293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
274402293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
274502293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
274602293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
274702293ed7STobias Grosser         isl_set_free(Dom);
27489e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
27499e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
27509e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
27519e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
275202293ed7STobias Grosser       } else {
275360f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
275460f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
275560f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
275660f63b49STobias Grosser         isl_set_free(Dom);
275760f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
275802293ed7STobias Grosser         isl_local_space *LS =
275902293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
276060f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
276160f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
276260f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
276360f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
27649e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27659e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27669e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
276760f63b49STobias Grosser       }
276802293ed7STobias Grosser     }
276960f63b49STobias Grosser 
277060f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
277177eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
277260f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
277360f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
277460f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
27759e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27769e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27779e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
277860f63b49STobias Grosser     }
27799e3db2b7SSiddharth Bhat 
27809e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
27819e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
27829e3db2b7SSiddharth Bhat 
27839e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
27849e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
27859e3db2b7SSiddharth Bhat 
27869e3db2b7SSiddharth Bhat     PPCGArray.bound =
27879e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
27889e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
278960f63b49STobias Grosser   }
279060f63b49STobias Grosser 
279160f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
279260f63b49STobias Grosser   ///
279360f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
279443f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
279543f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
279660f63b49STobias Grosser     int i = 0;
279743f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
279860f63b49STobias Grosser       std::string TypeName;
279960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
280060f63b49STobias Grosser 
280160f63b49STobias Grosser       OS << *Array->getElementType();
280260f63b49STobias Grosser       TypeName = OS.str();
280360f63b49STobias Grosser 
280460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
280560f63b49STobias Grosser 
280677eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
280760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
280860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
280960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
281060f63b49STobias Grosser       PPCGArray.extent = nullptr;
281160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
281260f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
281360f63b49STobias Grosser       PPCGArray.n_ref = 0;
281460f63b49STobias Grosser       PPCGArray.refs = nullptr;
281560f63b49STobias Grosser       PPCGArray.accessed = true;
2816fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2817fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
281860f63b49STobias Grosser       PPCGArray.has_compound_element = false;
281960f63b49STobias Grosser       PPCGArray.local = false;
282060f63b49STobias Grosser       PPCGArray.declare_local = false;
282160f63b49STobias Grosser       PPCGArray.global = false;
282260f63b49STobias Grosser       PPCGArray.linearize = false;
282360f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
282413c78e4dSTobias Grosser       PPCGArray.user = Array;
282560f63b49STobias Grosser 
28269e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
282760f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
28282d010dafSTobias Grosser       i++;
2829b9fc860aSTobias Grosser 
2830b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
283160f63b49STobias Grosser     }
283260f63b49STobias Grosser   }
283360f63b49STobias Grosser 
283460f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
283560f63b49STobias Grosser   ///
283660f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
283760f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
283860f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
283960f63b49STobias Grosser 
2840d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
284177eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
284260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
284360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
284460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
284560f63b49STobias Grosser     }
284660f63b49STobias Grosser 
284760f63b49STobias Grosser     return Maps;
284860f63b49STobias Grosser   }
284960f63b49STobias Grosser 
2850e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2851e938517eSTobias Grosser   ///
2852a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2853e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2854e938517eSTobias Grosser 
2855e938517eSTobias Grosser     if (!PPCGScop)
2856e938517eSTobias Grosser       return nullptr;
2857e938517eSTobias Grosser 
2858e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2859e938517eSTobias Grosser 
2860e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2861e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2862aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
286360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
286460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
286560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
286660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
286760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
286860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
286960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
28709e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2871e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2872a82f2d26SSiddharth Bhat 
2873a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2874a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2875a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2876a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2877a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2878a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
287969b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
288069b46751STobias Grosser     PPCGProg->stmts = getStatements();
288143f178bbSSiddharth Bhat 
288243f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
288343f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
288443f178bbSSiddharth Bhat     // empty arrays:
288543f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
288643f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
288743f178bbSSiddharth Bhat     auto ValidSAIsRange =
288843f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
288943f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
289043f178bbSSiddharth Bhat         });
289143f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
289243f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
289343f178bbSSiddharth Bhat 
289443f178bbSSiddharth Bhat     PPCGProg->n_array =
289543f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
289660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
289760f63b49STobias Grosser                                        PPCGProg->n_array);
289860f63b49STobias Grosser 
289943f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2900e938517eSTobias Grosser 
2901d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2902e938517eSTobias Grosser     return PPCGProg;
2903e938517eSTobias Grosser   }
2904e938517eSTobias Grosser 
290569b46751STobias Grosser   struct PrintGPUUserData {
290669b46751STobias Grosser     struct cuda_info *CudaInfo;
290769b46751STobias Grosser     struct gpu_prog *PPCGProg;
290869b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
290969b46751STobias Grosser   };
291069b46751STobias Grosser 
291169b46751STobias Grosser   /// Print a user statement node in the host code.
291269b46751STobias Grosser   ///
291369b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
291469b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
291569b46751STobias Grosser   /// host ast.
291669b46751STobias Grosser   ///
291769b46751STobias Grosser   /// @param P The printer to print to
291869b46751STobias Grosser   /// @param Options The printing options to use
291969b46751STobias Grosser   /// @param Node The node to print
292069b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
292169b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
292269b46751STobias Grosser   ///
292369b46751STobias Grosser   /// @returns A printer to which the output has been printed.
292469b46751STobias Grosser   static __isl_give isl_printer *
292569b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
292669b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
292769b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
292869b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
292969b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
293069b46751STobias Grosser 
293169b46751STobias Grosser     if (Id) {
293220251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
293320251734STobias Grosser 
293420251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
293520251734STobias Grosser       // otherwise try to call pet functionality that is not available in
293620251734STobias Grosser       // Polly.
293720251734STobias Grosser       if (IsUser) {
293820251734STobias Grosser         P = isl_printer_start_line(P);
293920251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
294020251734STobias Grosser         P = isl_printer_end_line(P);
294120251734STobias Grosser         isl_id_free(Id);
294220251734STobias Grosser         isl_ast_print_options_free(Options);
294320251734STobias Grosser         return P;
294420251734STobias Grosser       }
294520251734STobias Grosser 
294669b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
294769b46751STobias Grosser       isl_id_free(Id);
294869b46751STobias Grosser       Data->Kernels.push_back(Kernel);
294969b46751STobias Grosser     }
295069b46751STobias Grosser 
295169b46751STobias Grosser     return print_host_user(P, Options, Node, User);
295269b46751STobias Grosser   }
295369b46751STobias Grosser 
295469b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
295569b46751STobias Grosser   ///
295669b46751STobias Grosser   /// @param Kernel The kernel to print
295769b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
295869b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
295969b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
296069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
296169b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
296269b46751STobias Grosser     char *String = isl_printer_get_str(P);
296369b46751STobias Grosser     printf("%s\n", String);
296469b46751STobias Grosser     free(String);
296569b46751STobias Grosser     isl_printer_free(P);
296669b46751STobias Grosser   }
296769b46751STobias Grosser 
296869b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
296969b46751STobias Grosser   ///
297069b46751STobias Grosser   /// @param Tree An AST describing GPU code
297169b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
297269b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
297369b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
297469b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
297569b46751STobias Grosser 
297669b46751STobias Grosser     PrintGPUUserData Data;
297769b46751STobias Grosser     Data.PPCGProg = PPCGProg;
297869b46751STobias Grosser 
297969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
298069b46751STobias Grosser     Options =
298169b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
298269b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
298369b46751STobias Grosser     char *String = isl_printer_get_str(P);
298469b46751STobias Grosser     printf("# host\n");
298569b46751STobias Grosser     printf("%s\n", String);
298669b46751STobias Grosser     free(String);
298769b46751STobias Grosser     isl_printer_free(P);
298869b46751STobias Grosser 
298969b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
299069b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
299169b46751STobias Grosser       printKernel(Kernel);
299269b46751STobias Grosser     }
299369b46751STobias Grosser   }
299469b46751STobias Grosser 
2995f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2996f384594dSTobias Grosser   //
2997f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2998f384594dSTobias Grosser   //
2999f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3000f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3001f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3002f384594dSTobias Grosser   //
3003f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3004f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3005f384594dSTobias Grosser   // strategy directly from this pass.
3006f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3007f384594dSTobias Grosser 
3008f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3009f384594dSTobias Grosser 
3010f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3011f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3012f384594dSTobias Grosser     PPCGGen->print = nullptr;
3013f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
301460c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3015f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3016f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3017f384594dSTobias Grosser     PPCGGen->types.n = 0;
3018f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3019f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3020f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3021f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3022f384594dSTobias Grosser 
3023f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3024f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3025f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
30262341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3027f384594dSTobias Grosser 
3028f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3029f384594dSTobias Grosser 
3030aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3031aef5196fSTobias Grosser 
303269b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3033aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
303469b46751STobias Grosser     } else {
3035aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
303669b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
303769b46751STobias Grosser     }
3038aef5196fSTobias Grosser 
3039f384594dSTobias Grosser     if (DumpSchedule) {
3040f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3041f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3042f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3043f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3044f384594dSTobias Grosser       if (Schedule)
3045f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3046f384594dSTobias Grosser       else
3047f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3048f384594dSTobias Grosser 
3049f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3050f384594dSTobias Grosser       isl_printer_free(P);
3051f384594dSTobias Grosser     }
3052f384594dSTobias Grosser 
305369b46751STobias Grosser     if (DumpCode) {
305469b46751STobias Grosser       printf("Code\n");
305569b46751STobias Grosser       printf("====\n");
305669b46751STobias Grosser       if (PPCGGen->tree)
305769b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
305869b46751STobias Grosser       else
305969b46751STobias Grosser         printf("No code generated\n");
306069b46751STobias Grosser     }
306169b46751STobias Grosser 
3062f384594dSTobias Grosser     isl_schedule_free(Schedule);
3063f384594dSTobias Grosser 
3064f384594dSTobias Grosser     return PPCGGen;
3065f384594dSTobias Grosser   }
3066f384594dSTobias Grosser 
3067f384594dSTobias Grosser   /// Free gpu_gen structure.
3068f384594dSTobias Grosser   ///
3069f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3070f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3071f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3072f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3073f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3074f384594dSTobias Grosser     free(PPCGGen);
3075f384594dSTobias Grosser   }
3076f384594dSTobias Grosser 
3077b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3078b307ed4dSTobias Grosser   ///
3079b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3080b307ed4dSTobias Grosser   /// ourselves.
3081b307ed4dSTobias Grosser   ///
3082b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3083b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3084b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3085b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3086b307ed4dSTobias Grosser     free(PPCGScop->options);
3087b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3088b307ed4dSTobias Grosser   }
3089b307ed4dSTobias Grosser 
309082f2af35STobias Grosser   /// Approximate the number of points in the set.
309182f2af35STobias Grosser   ///
309282f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
309382f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
309482f2af35STobias Grosser   ///
309582f2af35STobias Grosser   /// @param Set   The set to count.
309682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
309782f2af35STobias Grosser   ///              expression.
309882f2af35STobias Grosser   ///
309982f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
310082f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
310182f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
310282f2af35STobias Grosser 
310382f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
310482f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
310582f2af35STobias Grosser 
310682f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
310782f2af35STobias Grosser     Space = isl_space_params(Space);
310882f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
310982f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
311082f2af35STobias Grosser 
311182f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
311282f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
311382f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
311482f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
311582f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
311682f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
311782f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
311882f2af35STobias Grosser     }
311982f2af35STobias Grosser 
312082f2af35STobias Grosser     isl_set_free(Set);
312182f2af35STobias Grosser     isl_pw_aff_free(OneAff);
312282f2af35STobias Grosser 
312382f2af35STobias Grosser     return Expr;
312482f2af35STobias Grosser   }
312582f2af35STobias Grosser 
312682f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
312782f2af35STobias Grosser   /// statement.
312882f2af35STobias Grosser   ///
312982f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
313082f2af35STobias Grosser   ///              instructions.
313182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
313282f2af35STobias Grosser   ///              expression.
313382f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
313482f2af35STobias Grosser   ///          by @p Stmt.
313582f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
313682f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
313782f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
313882f2af35STobias Grosser 
313982f2af35STobias Grosser     long InstCount = 0;
314082f2af35STobias Grosser 
314182f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
314282f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
314382f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
314482f2af35STobias Grosser     } else {
314582f2af35STobias Grosser       auto *R = Stmt.getRegion();
314682f2af35STobias Grosser 
314782f2af35STobias Grosser       for (auto *BB : R->blocks()) {
314882f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
314982f2af35STobias Grosser       }
315082f2af35STobias Grosser     }
315182f2af35STobias Grosser 
315282f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
315382f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
315482f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
315582f2af35STobias Grosser   }
315682f2af35STobias Grosser 
315782f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
315882f2af35STobias Grosser   ///
315982f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
316082f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
316182f2af35STobias Grosser   ///              expression.
316282f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
316382f2af35STobias Grosser   ///          in @p S.
316482f2af35STobias Grosser   __isl_give isl_ast_expr *
316582f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
316682f2af35STobias Grosser     isl_ast_expr *Instructions;
316782f2af35STobias Grosser 
316882f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
316982f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
317082f2af35STobias Grosser 
317182f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
317282f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
317382f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
317482f2af35STobias Grosser     }
317582f2af35STobias Grosser     return Instructions;
317682f2af35STobias Grosser   }
317782f2af35STobias Grosser 
317882f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
317982f2af35STobias Grosser   ///
318082f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
318182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
318282f2af35STobias Grosser   ///              expression.
318382f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
318482f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
318582f2af35STobias Grosser   __isl_give isl_ast_expr *
318682f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
318782f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
318882f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
318982f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
319082f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
319182f2af35STobias Grosser   }
319282f2af35STobias Grosser 
3193f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3194f291c8d5SSiddharth Bhat   /// kernels.
3195f291c8d5SSiddharth Bhat   ///
3196f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3197f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
31988fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
31998fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3200f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3201f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
32028fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
32038fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3204f291c8d5SSiddharth Bhat         continue;
3205f291c8d5SSiddharth Bhat       }
3206f291c8d5SSiddharth Bhat 
3207bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3208bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3209bccaea57SSiddharth Bhat         if (!p)
3210bccaea57SSiddharth Bhat           continue;
3211bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3212bccaea57SSiddharth Bhat           return true;
3213bccaea57SSiddharth Bhat       }
3214f291c8d5SSiddharth Bhat     }
3215bccaea57SSiddharth Bhat     return false;
3216bccaea57SSiddharth Bhat   }
3217bccaea57SSiddharth Bhat 
3218f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
32198fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3220bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3221bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
32228fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
32238fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3224bccaea57SSiddharth Bhat           return true;
3225bccaea57SSiddharth Bhat       } else {
3226bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3227bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3228bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
32298fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3230bccaea57SSiddharth Bhat             return true;
3231bccaea57SSiddharth Bhat       }
3232bccaea57SSiddharth Bhat     }
3233bccaea57SSiddharth Bhat     return false;
3234bccaea57SSiddharth Bhat   }
3235bccaea57SSiddharth Bhat 
323638fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
323738fc0aedSTobias Grosser   ///
323832837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
323932837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
324032837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
324138fc0aedSTobias Grosser     ScopAnnotator Annotator;
324238fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
324338fc0aedSTobias Grosser 
324438fc0aedSTobias Grosser     Region *R = &S->getRegion();
324538fc0aedSTobias Grosser 
324638fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
324738fc0aedSTobias Grosser 
324838fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
324938fc0aedSTobias Grosser 
325038fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
325138fc0aedSTobias Grosser 
325238fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
325338fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
325438fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
325538fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
325638fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
325738fc0aedSTobias Grosser     // code generating this scop.
325803346c27SSiddharth Bhat     BBPair StartExitBlocks;
325903346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
326003346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
32612d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3262256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
326338fc0aedSTobias Grosser 
326403346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
326503346c27SSiddharth Bhat 
32662d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
326717f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3268acf80064SEli Friedman 
326938fc0aedSTobias Grosser     // TODO: Handle LICM
327038fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
327138fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
327238fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3273cb1aef8dSTobias Grosser 
3274cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
32752b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
327682f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
327782f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3278cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3279cb1aef8dSTobias Grosser 
32809e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
32819e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
32824ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
32834ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
32844ebeb356SSiddharth Bhat                          S->getFunction().getName() +
32854ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
32869e3db2b7SSiddharth Bhat 
3287cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3288cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3289cb1aef8dSTobias Grosser 
329038fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3291fa7b0802STobias Grosser 
329238fc0aedSTobias Grosser     NodeBuilder.create(Root);
32935857b701STobias Grosser 
3294bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3295bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3296de244eb4STobias Grosser     /// point in running it on a GPU.
3297bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
329803346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3299bc653f20STobias Grosser 
33005857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
330103346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
330238fc0aedSTobias Grosser   }
330338fc0aedSTobias Grosser 
3304e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3305e938517eSTobias Grosser     S = &CurrentScop;
330638fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
330738fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
330838fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
33097b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
331038fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3311e938517eSTobias Grosser 
3312f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3313f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3314f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3315bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3316bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
33178fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
33188fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3319f291c8d5SSiddharth Bhat       DEBUG(
3320f291c8d5SSiddharth Bhat           dbgs()
3321f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3322f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3323bccaea57SSiddharth Bhat       return false;
3324f291c8d5SSiddharth Bhat     }
3325bccaea57SSiddharth Bhat 
3326e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3327e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3328f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
332938fc0aedSTobias Grosser 
333002ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
333132837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
333202ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
333302ca346eSSingapuram Sanjay Srivallabh     }
333438fc0aedSTobias Grosser 
3335b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3336f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3337e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3338e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3339e938517eSTobias Grosser 
3340e938517eSTobias Grosser     return true;
3341e938517eSTobias Grosser   }
33429dfe4e7cSTobias Grosser 
33439dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
33449dfe4e7cSTobias Grosser 
33459dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
33469dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
33479dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
33489dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
33495cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
33509dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
33519dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
33529dfe4e7cSTobias Grosser 
33539dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
33549dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
33559dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
33569dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
33579dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
33585cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
33599dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
33609dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
33619dfe4e7cSTobias Grosser 
33629dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
33639dfe4e7cSTobias Grosser     //        region tree.
33649dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
33659dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
33669dfe4e7cSTobias Grosser   }
33679dfe4e7cSTobias Grosser };
336824222c73STobias Grosser } // namespace
33699dfe4e7cSTobias Grosser 
33709dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
33719dfe4e7cSTobias Grosser 
337217f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
337317f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
337417f01968SSiddharth Bhat   generator->Runtime = Runtime;
337517f01968SSiddharth Bhat   generator->Architecture = Arch;
337617f01968SSiddharth Bhat   return generator;
337717f01968SSiddharth Bhat }
33789dfe4e7cSTobias Grosser 
33799dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
33809dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
33819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
33829dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
33839dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
33849dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
33859dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
33865cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
33879dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
33889dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3389