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 
1060*ccbf4b50SSiddharth Bhat   isl::ast_build Build =
1061*ccbf4b50SSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
1062aaabbbf8STobias Grosser 
1063*ccbf4b50SSiddharth Bhat   isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin();
1064aaabbbf8STobias Grosser 
1065*ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1066aaabbbf8STobias Grosser 
1067*ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++)
1068*ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1069aaabbbf8STobias Grosser 
1070*ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1071aaabbbf8STobias Grosser     return nullptr;
1072aaabbbf8STobias Grosser   }
1073aaabbbf8STobias Grosser 
1074*ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1075aaabbbf8STobias Grosser 
1076*ccbf4b50SSiddharth Bhat   for (long i = 0; i < Min.dim(isl::dim::set); i++) {
1077aaabbbf8STobias Grosser     if (i > 0) {
1078*ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1079*ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1080*ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1081*ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1082aaabbbf8STobias Grosser     }
1083*ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1084*ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1085*ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1086aaabbbf8STobias Grosser   }
1087aaabbbf8STobias Grosser 
1088*ccbf4b50SSiddharth 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();
1107abed4969SSiddharth Bhat 
1108abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1109abed4969SSiddharth Bhat     if (Offset) {
1110abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1111abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1112abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1113abed4969SSiddharth Bhat     }
1114abed4969SSiddharth Bhat 
1115abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1116abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1117abed4969SSiddharth Bhat     return HostPtr;
1118abed4969SSiddharth Bhat   }
1119abed4969SSiddharth Bhat }
1120abed4969SSiddharth Bhat 
112113c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
112213c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1123abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
112413c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
112513c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
112613c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
112713c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
112813c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
112913c78e4dSTobias Grosser 
113013c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1131aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
113213c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
113313c78e4dSTobias Grosser 
1134b06ff457STobias Grosser   Value *HostPtr;
1135b06ff457STobias Grosser 
1136b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1137b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1138b06ff457STobias Grosser   else
1139b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
114013c78e4dSTobias Grosser 
1141aaabbbf8STobias Grosser   if (Offset) {
1142aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1143aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1144aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1145aaabbbf8STobias Grosser   }
1146aaabbbf8STobias Grosser 
114713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
114813c78e4dSTobias Grosser 
1149aaabbbf8STobias Grosser   if (Offset) {
1150aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1151ff40087aSTobias Grosser         Size, Builder.CreateMul(
1152ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1153aaabbbf8STobias Grosser   }
1154aaabbbf8STobias Grosser 
115513c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
115613c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
115713c78e4dSTobias Grosser   else
115813c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
115913c78e4dSTobias Grosser 
116013c78e4dSTobias Grosser   isl_id_free(Id);
116113c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
116213c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
116313c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
116413c78e4dSTobias Grosser }
116513c78e4dSTobias Grosser 
11661fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
116732837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
116832837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
116932837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
117032837fe3STobias Grosser   isl_id_free(Id);
117132837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
117232837fe3STobias Grosser 
117332837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
117432837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
117532837fe3STobias Grosser     createKernel(UserStmt);
117632837fe3STobias Grosser     isl_ast_expr_free(Expr);
117732837fe3STobias Grosser     return;
117832837fe3STobias Grosser   }
11799e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11809e3db2b7SSiddharth Bhat     initializeAfterRTH();
11819e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11829e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11839e3db2b7SSiddharth Bhat     return;
11849e3db2b7SSiddharth Bhat   }
11859e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11869e3db2b7SSiddharth Bhat     finalize();
11879e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11889e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11899e3db2b7SSiddharth Bhat     return;
11909e3db2b7SSiddharth Bhat   }
119113c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1192abed4969SSiddharth Bhat     if (!ManagedMemory)
119313c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1194abed4969SSiddharth Bhat     else
1195abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1196abed4969SSiddharth Bhat 
119732837fe3STobias Grosser     isl_ast_expr_free(Expr);
119813c78e4dSTobias Grosser     return;
119913c78e4dSTobias Grosser   }
120013c78e4dSTobias Grosser 
120113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1202abed4969SSiddharth Bhat     if (!ManagedMemory) {
120313c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1204abed4969SSiddharth Bhat     } else {
1205abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1206abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1207abed4969SSiddharth Bhat     }
120813c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
120938fc0aedSTobias Grosser     return;
121038fc0aedSTobias Grosser   }
121138fc0aedSTobias Grosser 
12125260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12135260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12145260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12155260c041STobias Grosser   isl_id_free(Anno);
12165260c041STobias Grosser 
12175260c041STobias Grosser   switch (KernelStmt->type) {
12185260c041STobias Grosser   case ppcg_kernel_domain:
1219edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12205260c041STobias Grosser     isl_ast_node_free(UserStmt);
12215260c041STobias Grosser     return;
12225260c041STobias Grosser   case ppcg_kernel_copy:
1223b513b491STobias Grosser     createKernelCopy(KernelStmt);
12245260c041STobias Grosser     isl_ast_expr_free(Expr);
12255260c041STobias Grosser     isl_ast_node_free(UserStmt);
12265260c041STobias Grosser     return;
12275260c041STobias Grosser   case ppcg_kernel_sync:
12285260c041STobias Grosser     createKernelSync();
12295260c041STobias Grosser     isl_ast_expr_free(Expr);
12305260c041STobias Grosser     isl_ast_node_free(UserStmt);
12315260c041STobias Grosser     return;
12325260c041STobias Grosser   }
12335260c041STobias Grosser 
12345260c041STobias Grosser   isl_ast_expr_free(Expr);
12355260c041STobias Grosser   isl_ast_node_free(UserStmt);
12365260c041STobias Grosser   return;
12375260c041STobias Grosser }
1238b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1239b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1240b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1241b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1242b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1243b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1244b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1245b513b491STobias Grosser 
1246b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1247b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1248b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1249b513b491STobias Grosser   } else {
1250b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1251b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1252b513b491STobias Grosser   }
1253b513b491STobias Grosser }
12545260c041STobias Grosser 
1255edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1256edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1257edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1258edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1259edb885cbSTobias Grosser 
1260edb885cbSTobias Grosser   LoopToScevMapT LTS;
1261edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1262edb885cbSTobias Grosser 
1263edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1264edb885cbSTobias Grosser 
1265edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1266edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1267edb885cbSTobias Grosser   else
1268a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1269edb885cbSTobias Grosser }
1270edb885cbSTobias Grosser 
12715260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12725260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12732f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
127417f01968SSiddharth Bhat 
127517f01968SSiddharth Bhat   Function *Sync;
127617f01968SSiddharth Bhat 
127717f01968SSiddharth Bhat   switch (Arch) {
12782f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12792f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12802f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12812f3073b5SPhilipp Schaad 
12822f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12832f3073b5SPhilipp Schaad     if (!Sync) {
12842f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
12852f3073b5SPhilipp Schaad       std::vector<Type *> Args;
12862f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
12872f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
12882f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
12892f3073b5SPhilipp Schaad     }
12902f3073b5SPhilipp Schaad     break;
129117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
129217f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
129317f01968SSiddharth Bhat     break;
129417f01968SSiddharth Bhat   }
129517f01968SSiddharth Bhat 
12965260c041STobias Grosser   Builder.CreateCall(Sync, {});
12975260c041STobias Grosser }
12985260c041STobias Grosser 
1299edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1300edb885cbSTobias Grosser ///
1301edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1302edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1303edb885cbSTobias Grosser ///
1304edb885cbSTobias Grosser /// @param Node The node to collect references for.
1305edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1306edb885cbSTobias Grosser ///
1307edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1308edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1309edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1310edb885cbSTobias Grosser     return isl_bool_true;
1311edb885cbSTobias Grosser 
1312edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1313edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1314edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1315edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1316edb885cbSTobias Grosser   isl_id_free(Id);
1317edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1318edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1319edb885cbSTobias Grosser 
1320edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1321edb885cbSTobias Grosser     return isl_bool_true;
1322edb885cbSTobias Grosser 
1323edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1324edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1325edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1326edb885cbSTobias Grosser   isl_id_free(Id);
1327edb885cbSTobias Grosser 
132800bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1329edb885cbSTobias Grosser 
1330edb885cbSTobias Grosser   return isl_bool_true;
1331edb885cbSTobias Grosser }
1332edb885cbSTobias Grosser 
13338fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13348fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
13358fc6cdfbSTobias Grosser     "exp",  "expf",  "expl",     "cos",       "cosf",
13368fc6cdfbSTobias Grosser     "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"};
13378fc6cdfbSTobias Grosser 
13388fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F.
13398fc6cdfbSTobias Grosser ///
13408fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
13418fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) {
13428fc6cdfbSTobias Grosser   if (CUDALibDeviceFunctions.count(F->getName()))
13438fc6cdfbSTobias Grosser     return std::string("__nv_") + std::string(F->getName());
13448fc6cdfbSTobias Grosser 
13458fc6cdfbSTobias Grosser   return "";
13468fc6cdfbSTobias Grosser }
13478fc6cdfbSTobias Grosser 
1348f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
13498fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1350f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1351f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
135254491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
135354491db6STobias Grosser   // "llvm.copysign".
135454491db6STobias Grosser   const StringRef Name = F->getName();
13558fc6cdfbSTobias Grosser 
13568fc6cdfbSTobias Grosser   if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0)
13578fc6cdfbSTobias Grosser     return true;
13588fc6cdfbSTobias Grosser 
135954491db6STobias Grosser   return F->isIntrinsic() &&
136054491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
136154491db6STobias Grosser           Name.startswith("llvm.copysign"));
1362f291c8d5SSiddharth Bhat }
1363f291c8d5SSiddharth Bhat 
1364f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1365f291c8d5SSiddharth Bhat ///
1366f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1367f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1368f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1369f291c8d5SSiddharth Bhat /// `Function`s.
1370f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1371f291c8d5SSiddharth Bhat 
1372f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1373f291c8d5SSiddharth Bhat static SetVector<Function *>
13748fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
13758fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1376f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1377f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1378f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1379f291c8d5SSiddharth Bhat     if (F) {
13808fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
13818fc6cdfbSTobias Grosser              "Code should have bailed out by "
1382f291c8d5SSiddharth Bhat              "this point if an invalid function "
1383f291c8d5SSiddharth Bhat              "were present in a kernel.");
1384f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1385f291c8d5SSiddharth Bhat     }
1386f291c8d5SSiddharth Bhat   }
1387f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1388f291c8d5SSiddharth Bhat }
1389f291c8d5SSiddharth Bhat 
1390f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1391f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1392edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1393edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1394edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1395edb885cbSTobias Grosser   SubtreeReferences References = {
1396edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1397edb885cbSTobias Grosser 
1398edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1399edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1400edb885cbSTobias Grosser 
1401edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1402edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1403edb885cbSTobias Grosser 
1404edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1405edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1406edb885cbSTobias Grosser 
1407edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1408d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1409edb885cbSTobias Grosser 
1410edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1411edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1412edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1413edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1414edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1415edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1416edb885cbSTobias Grosser     isl_id_free(Id);
1417edb885cbSTobias Grosser   }
1418edb885cbSTobias Grosser   isl_space_free(Space);
1419edb885cbSTobias Grosser 
1420edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1421edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1422edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1423edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1424edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1425edb885cbSTobias Grosser     isl_id_free(Id);
1426edb885cbSTobias Grosser   }
1427edb885cbSTobias Grosser 
1428f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1429f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1430f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1431f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1432f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1433f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1434f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1435f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1436f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
14378fc6cdfbSTobias Grosser 
14388fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
14398fc6cdfbSTobias Grosser 
1440f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
14418fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1442f291c8d5SSiddharth Bhat 
1443a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1444a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1445a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1446a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1447a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1448a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1449a1b2086aSSiddharth Bhat     else
1450a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1451a1b2086aSSiddharth Bhat   }
1452a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1453edb885cbSTobias Grosser }
1454edb885cbSTobias Grosser 
145574dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
145674dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
145774dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
145874dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
145974dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
146074dc3cb4STobias Grosser 
146174dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
146274dc3cb4STobias Grosser     DT.eraseNode(BB);
146374dc3cb4STobias Grosser }
146474dc3cb4STobias Grosser 
146574dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
146674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
146774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
146874dc3cb4STobias Grosser     if (L)
146974dc3cb4STobias Grosser       SE.forgetLoop(L);
147074dc3cb4STobias Grosser   }
147174dc3cb4STobias Grosser }
147274dc3cb4STobias Grosser 
147374dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
147474dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
147574dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
147674dc3cb4STobias Grosser     if (L)
147774dc3cb4STobias Grosser       SE.forgetLoop(L);
147874dc3cb4STobias Grosser     LI.removeBlock(&BB);
147974dc3cb4STobias Grosser   }
148074dc3cb4STobias Grosser }
148174dc3cb4STobias Grosser 
148279a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
148379a947c2STobias Grosser   std::vector<Value *> Sizes;
148479a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
148579a947c2STobias Grosser 
148679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
148779a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
148879a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
148979a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
149079a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
149179a947c2STobias Grosser     Sizes.push_back(Res);
149279a947c2STobias Grosser   }
149379a947c2STobias Grosser   isl_ast_build_free(Context);
149479a947c2STobias Grosser 
149579a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
149679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
149779a947c2STobias Grosser 
149879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
149979a947c2STobias Grosser }
150079a947c2STobias Grosser 
150179a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
150279a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
150379a947c2STobias Grosser   std::vector<Value *> Sizes;
150479a947c2STobias Grosser 
150579a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
150679a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
150779a947c2STobias Grosser     Sizes.push_back(Res);
150879a947c2STobias Grosser   }
150979a947c2STobias Grosser 
151079a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
151179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
151279a947c2STobias Grosser 
151379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
151479a947c2STobias Grosser }
151579a947c2STobias Grosser 
1516a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1517a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1518a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1519a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1520a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1521a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1522a90be207SSiddharth Bhat }
1523a90be207SSiddharth Bhat 
152457693272STobias Grosser Value *
152557693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
152657693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1527a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1528a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1529a90be207SSiddharth Bhat 
1530a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
153179a947c2STobias Grosser 
153279a947c2STobias Grosser   BasicBlock *EntryBlock =
153379a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
153467726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
153579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
153667726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
153767726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
153879a947c2STobias Grosser 
153979a947c2STobias Grosser   int Index = 0;
154079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
154179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
154279a947c2STobias Grosser       continue;
154379a947c2STobias Grosser 
154479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1545206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
154679a947c2STobias Grosser 
1547a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1548a90be207SSiddharth Bhat 
1549abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1550abed4969SSiddharth Bhat     if (ManagedMemory) {
1551abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1552abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1553abed4969SSiddharth Bhat     } else {
1554abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
155579a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1556abed4969SSiddharth Bhat     }
1557abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1558abed4969SSiddharth Bhat                                   "initialized");
1559aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1560aaabbbf8STobias Grosser 
1561aaabbbf8STobias Grosser     if (Offset) {
1562aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1563aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1564aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1565aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1566aaabbbf8STobias Grosser     }
1567fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1568fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1569aaabbbf8STobias Grosser 
1570fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1571abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1572abed4969SSiddharth Bhat       if (ManagedMemory)
1573abed4969SSiddharth Bhat         ValPtr = DevArray;
1574abed4969SSiddharth Bhat       else
1575abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1576abed4969SSiddharth Bhat 
1577abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1578abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1579fe74a7a1STobias Grosser       Value *ValPtrCast =
1580fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1581fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1582fe74a7a1STobias Grosser     } else {
158367726b32STobias Grosser       Instruction *Param =
158467726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
158567726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
158679a947c2STobias Grosser                          EntryBlock->getTerminator());
158779a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
158879a947c2STobias Grosser       Value *ParamTyped =
158979a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
159079a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1591fe74a7a1STobias Grosser     }
159279a947c2STobias Grosser     Index++;
159379a947c2STobias Grosser   }
159479a947c2STobias Grosser 
1595a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1596a490147cSTobias Grosser 
1597a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1598a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1599a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1600a490147cSTobias Grosser     isl_id_free(Id);
1601a90be207SSiddharth Bhat 
1602a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1603a90be207SSiddharth Bhat 
160467726b32STobias Grosser     Instruction *Param =
160567726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
160667726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1607a490147cSTobias Grosser                        EntryBlock->getTerminator());
1608a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1609a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1610a490147cSTobias Grosser     Index++;
1611a490147cSTobias Grosser   }
1612a490147cSTobias Grosser 
1613d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1614d8b94bcaSTobias Grosser 
1615d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1616d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1617d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1618a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1619a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1620d8b94bcaSTobias Grosser     isl_id_free(Id);
1621a90be207SSiddharth Bhat 
1622a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1623a90be207SSiddharth Bhat 
162467726b32STobias Grosser     Instruction *Param =
162567726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
162667726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1627d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1628d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1629a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1630d8b94bcaSTobias Grosser     Index++;
1631d8b94bcaSTobias Grosser   }
1632d8b94bcaSTobias Grosser 
163357693272STobias Grosser   for (auto Val : SubtreeValues) {
1634a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1635a90be207SSiddharth Bhat 
163667726b32STobias Grosser     Instruction *Param =
163767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
163867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
163957693272STobias Grosser                        EntryBlock->getTerminator());
164057693272STobias Grosser     Builder.CreateStore(Val, Param);
1641a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1642a90be207SSiddharth Bhat     Index++;
1643a90be207SSiddharth Bhat   }
1644a90be207SSiddharth Bhat 
1645a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1646a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1647a90be207SSiddharth Bhat     Instruction *Param =
1648a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1649a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1650a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1651a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1652a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
165357693272STobias Grosser     Index++;
165457693272STobias Grosser   }
165557693272STobias Grosser 
165679a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
165779a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
165879a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
165979a947c2STobias Grosser }
166079a947c2STobias Grosser 
1661f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1662f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1663f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1664f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1665f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1666f291c8d5SSiddharth Bhat     if (!Clone)
1667f291c8d5SSiddharth Bhat       Clone =
1668f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1669f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1670f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1671f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1672f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1673f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1674f291c8d5SSiddharth Bhat   }
1675f291c8d5SSiddharth Bhat }
167632837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
167732837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
167832837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
167932837fe3STobias Grosser   isl_id_free(Id);
168032837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
168132837fe3STobias Grosser 
1682bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1683bc653f20STobias Grosser     DeepestParallel =
1684bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1685bc653f20STobias Grosser   else
1686bc653f20STobias Grosser     DeepestSequential =
1687bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1688bc653f20STobias Grosser 
1689c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1690c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1691c1c6a2a6STobias Grosser 
1692f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1693f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1694f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1695edb885cbSTobias Grosser 
169632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
169732837fe3STobias Grosser 
169832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1699472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1700edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1701587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1702b06ff457STobias Grosser   ScalarMap.clear();
170332837fe3STobias Grosser 
1704edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1705edb885cbSTobias Grosser 
1706edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1707edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1708edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1709edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1710edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1711edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1712edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1713edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1714edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1715edb885cbSTobias Grosser     SubtreeValues.insert(V);
1716edb885cbSTobias Grosser   }
1717edb885cbSTobias Grosser 
1718f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1719f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
172032837fe3STobias Grosser 
172159ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
172259ab0705STobias Grosser 
172351dfc275STobias Grosser   finalizeKernelArguments(Kernel);
172474dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
17252f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1726c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
172774dc3cb4STobias Grosser   clearDominators(F);
172874dc3cb4STobias Grosser   clearScalarEvolution(F);
172974dc3cb4STobias Grosser   clearLoops(F);
173074dc3cb4STobias Grosser 
1731472f9654STobias Grosser   IDToValue = HostIDs;
173232837fe3STobias Grosser 
1733b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1734b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1735edb885cbSTobias Grosser   EscapeMap.clear();
1736edb885cbSTobias Grosser   IDToSAI.clear();
173774dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
173874dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17394d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
174074dc3cb4STobias Grosser   LocalArrays.clear();
1741edb885cbSTobias Grosser 
174251dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
174351dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
174457693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
174579a947c2STobias Grosser 
174679f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
174757793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
174857793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
174957793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
175079a947c2STobias Grosser 
175179a947c2STobias Grosser   Value *GridDimX, *GridDimY;
175279a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
175379a947c2STobias Grosser 
175479a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
175579a947c2STobias Grosser                          BlockDimZ, Parameters);
175657793596STobias Grosser   createCallFreeKernel(GPUKernel);
1757b513b491STobias Grosser 
1758b513b491STobias Grosser   for (auto Id : KernelIds)
1759b513b491STobias Grosser     isl_id_free(Id);
1760b513b491STobias Grosser 
1761b513b491STobias Grosser   KernelIds.clear();
176232837fe3STobias Grosser }
176332837fe3STobias Grosser 
176432837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
176532837fe3STobias Grosser ///
176632837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
176732837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1768d277fedaSSiddharth Bhat   std::string Ret = "";
176932837fe3STobias Grosser 
1770d277fedaSSiddharth Bhat   if (!is64Bit) {
1771d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
177230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1773d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1774d277fedaSSiddharth Bhat   } else {
1775d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-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   }
177932837fe3STobias Grosser 
178032837fe3STobias Grosser   return Ret;
178132837fe3STobias Grosser }
178232837fe3STobias Grosser 
17832f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
17842f3073b5SPhilipp Schaad ///
17852f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
17862f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
17872f3073b5SPhilipp Schaad   std::string Ret = "";
17882f3073b5SPhilipp Schaad 
17892f3073b5SPhilipp Schaad   if (!is64Bit) {
17902f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
179130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17922f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17932f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17942f3073b5SPhilipp Schaad   } else {
17952f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
179630caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17972f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17982f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17992f3073b5SPhilipp Schaad   }
18002f3073b5SPhilipp Schaad 
18012f3073b5SPhilipp Schaad   return Ret;
18022f3073b5SPhilipp Schaad }
18032f3073b5SPhilipp Schaad 
1804edb885cbSTobias Grosser Function *
1805edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1806edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
180732837fe3STobias Grosser   std::vector<Type *> Args;
180879f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
180932837fe3STobias Grosser 
18102f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
18112f3073b5SPhilipp Schaad 
181232837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
181332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
181432837fe3STobias Grosser       continue;
181532837fe3STobias Grosser 
1816fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1817fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1818206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1819fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
18202f3073b5SPhilipp Schaad       MemoryType.push_back(
18212f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1822fe74a7a1STobias Grosser     } else {
1823d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1824d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
18252f3073b5SPhilipp Schaad       MemoryType.push_back(
18262f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
182732837fe3STobias Grosser     }
1828fe74a7a1STobias Grosser   }
182932837fe3STobias Grosser 
1830f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1831f6044bd0STobias Grosser 
18322f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1833f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18342f3073b5SPhilipp Schaad     MemoryType.push_back(
18352f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18362f3073b5SPhilipp Schaad   }
1837f6044bd0STobias Grosser 
1838c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1839c84a1995STobias Grosser 
1840cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1841cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1842cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1843cf66ef26STobias Grosser     isl_id_free(Id);
1844cf66ef26STobias Grosser     Args.push_back(Val->getType());
18452f3073b5SPhilipp Schaad     MemoryType.push_back(
18462f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1847cf66ef26STobias Grosser   }
1848c84a1995STobias Grosser 
18492f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1850edb885cbSTobias Grosser     Args.push_back(V->getType());
18512f3073b5SPhilipp Schaad     MemoryType.push_back(
18522f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18532f3073b5SPhilipp Schaad   }
1854edb885cbSTobias Grosser 
185532837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
185632837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
185732837fe3STobias Grosser                               GPUModule.get());
185817f01968SSiddharth Bhat 
18592f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18602f3073b5SPhilipp Schaad 
18612f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18622f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18632f3073b5SPhilipp Schaad   }
18642f3073b5SPhilipp Schaad 
18652f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18662f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18672f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18682f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18692f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18702f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
18712f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18722f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
18732f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18742f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
18752f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18762f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
18772f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18782f3073b5SPhilipp Schaad   }
18792f3073b5SPhilipp Schaad 
188017f01968SSiddharth Bhat   switch (Arch) {
188117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
188232837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
188317f01968SSiddharth Bhat     break;
18842f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
18852f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
18862f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
18872f3073b5SPhilipp Schaad     break;
188817f01968SSiddharth Bhat   }
188932837fe3STobias Grosser 
189032837fe3STobias Grosser   auto Arg = FN->arg_begin();
189132837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
189232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
189332837fe3STobias Grosser       continue;
189432837fe3STobias Grosser 
1895edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1896edb885cbSTobias Grosser 
1897edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1898206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1899206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1900edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1901edb885cbSTobias Grosser     Value *Val = &*Arg;
1902edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1903edb885cbSTobias Grosser     isl_ast_build *Build =
1904edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1905f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1906edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1907edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
19089e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1909edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1910edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1911edb885cbSTobias Grosser     }
1912edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
19134d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
191474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1915edb885cbSTobias Grosser 
1916edb885cbSTobias Grosser     isl_ast_build_free(Build);
1917b513b491STobias Grosser     KernelIds.push_back(Id);
1918edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
191932837fe3STobias Grosser     Arg++;
192032837fe3STobias Grosser   }
192132837fe3STobias Grosser 
1922f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1923f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1924f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1925f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1926f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1927f6044bd0STobias Grosser     Arg++;
1928f6044bd0STobias Grosser   }
1929f6044bd0STobias Grosser 
1930c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1931c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1932c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
193312453403STobias Grosser     Value *Val = IDToValue[Id];
193412453403STobias Grosser     ValueMap[Val] = &*Arg;
1935c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1936c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1937c84a1995STobias Grosser     Arg++;
1938c84a1995STobias Grosser   }
1939c84a1995STobias Grosser 
1940edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1941edb885cbSTobias Grosser     Arg->setName(V->getName());
1942edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1943edb885cbSTobias Grosser     Arg++;
1944edb885cbSTobias Grosser   }
1945edb885cbSTobias Grosser 
194632837fe3STobias Grosser   return FN;
194732837fe3STobias Grosser }
194832837fe3STobias Grosser 
1949472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
195017f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
195117f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1952472f9654STobias Grosser 
195317f01968SSiddharth Bhat   switch (Arch) {
19542f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19552f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19562f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
195717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
195817f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
195917f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
196017f01968SSiddharth Bhat 
196117f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
196217f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
196317f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
196417f01968SSiddharth Bhat     break;
196517f01968SSiddharth Bhat   }
1966472f9654STobias Grosser 
1967472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1968472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1969472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1970472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1971472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1972472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1973472f9654STobias Grosser     IDToValue[Id] = Val;
1974472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1975472f9654STobias Grosser   };
1976472f9654STobias Grosser 
1977472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1978472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1979472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1980472f9654STobias Grosser   }
1981472f9654STobias Grosser 
1982472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1983472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1984472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1985472f9654STobias Grosser   }
1986472f9654STobias Grosser }
1987472f9654STobias Grosser 
19882f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
19892f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
19902f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
19912f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
19922f3073b5SPhilipp Schaad 
19932f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
19942f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
19952f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
19962f3073b5SPhilipp Schaad 
19972f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
19982f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19992f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
20002f3073b5SPhilipp Schaad 
20012f3073b5SPhilipp Schaad     // If FN is not available, declare it.
20022f3073b5SPhilipp Schaad     if (!FN) {
20032f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
20042f3073b5SPhilipp Schaad       std::vector<Type *> Args;
20052f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
20062f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
20072f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
20082f3073b5SPhilipp Schaad     }
20092f3073b5SPhilipp Schaad 
20102f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
20112f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
20122f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
20132f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
20142f3073b5SPhilipp Schaad   };
20152f3073b5SPhilipp Schaad 
20162f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
20172f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
20182f3073b5SPhilipp Schaad 
20192f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
20202f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
20212f3073b5SPhilipp Schaad }
20222f3073b5SPhilipp Schaad 
202300bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
202400bb5a99STobias Grosser   auto Arg = FN->arg_begin();
202500bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
202600bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
202700bb5a99STobias Grosser       continue;
202800bb5a99STobias Grosser 
202900bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2030206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2031206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
203200bb5a99STobias Grosser     isl_id_free(Id);
203300bb5a99STobias Grosser 
203400bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
203500bb5a99STobias Grosser       Arg++;
203600bb5a99STobias Grosser       continue;
203700bb5a99STobias Grosser     }
203800bb5a99STobias Grosser 
2039fe74a7a1STobias Grosser     Value *Val = &*Arg;
2040fe74a7a1STobias Grosser 
2041fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
204200bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2043fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2044fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2045fe74a7a1STobias Grosser     }
2046fe74a7a1STobias Grosser 
2047fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
204800bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
204900bb5a99STobias Grosser 
205000bb5a99STobias Grosser     Arg++;
205100bb5a99STobias Grosser   }
205200bb5a99STobias Grosser }
205300bb5a99STobias Grosser 
205451dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
205551dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
205651dfc275STobias Grosser   auto Arg = FN->arg_begin();
205751dfc275STobias Grosser 
205851dfc275STobias Grosser   bool StoredScalar = false;
205951dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
206051dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
206151dfc275STobias Grosser       continue;
206251dfc275STobias Grosser 
206351dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2064206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2065206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
206651dfc275STobias Grosser     isl_id_free(Id);
206751dfc275STobias Grosser 
206851dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
206951dfc275STobias Grosser       Arg++;
207051dfc275STobias Grosser       continue;
207151dfc275STobias Grosser     }
207251dfc275STobias Grosser 
207351dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
207451dfc275STobias Grosser       Arg++;
207551dfc275STobias Grosser       continue;
207651dfc275STobias Grosser     }
207751dfc275STobias Grosser 
207851dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
207951dfc275STobias Grosser     Value *ArgPtr = &*Arg;
208051dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
208151dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
208251dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
208351dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
208451dfc275STobias Grosser     StoredScalar = true;
208551dfc275STobias Grosser 
208651dfc275STobias Grosser     Arg++;
208751dfc275STobias Grosser   }
208851dfc275STobias Grosser 
208951dfc275STobias Grosser   if (StoredScalar)
209051dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
209151dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
209251dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
209351dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
209451dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
209551dfc275STobias Grosser       BuildSuccessful = 0;
209651dfc275STobias Grosser }
209751dfc275STobias Grosser 
2098b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2099b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2100b513b491STobias Grosser 
2101b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2102b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2103b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2104206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2105b513b491STobias Grosser 
2106f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2107b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2108b513b491STobias Grosser 
2109f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2110928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2111b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2112f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2113b513b491STobias Grosser       isl_val_free(Val);
2114b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2115928d7573STobias Grosser     }
2116928d7573STobias Grosser 
2117928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2118928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2119928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2120928d7573STobias Grosser       isl_val_free(Val);
2121b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2122b513b491STobias Grosser     }
2123b513b491STobias Grosser 
2124130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2125130ca30fSTobias Grosser     Value *Allocation;
2126130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2127130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2128130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2129130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2130130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2131f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2132f919d8b3STobias Grosser 
2133130ca30fSTobias Grosser       Allocation = GlobalVar;
2134130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2135130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2136130ca30fSTobias Grosser     } else {
2137130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2138130ca30fSTobias Grosser     }
21394d5a9172STobias Grosser     SAI =
21404d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2141b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2142130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2143130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2144b513b491STobias Grosser     KernelIds.push_back(Id);
2145b513b491STobias Grosser     IDToSAI[Id] = SAI;
2146b513b491STobias Grosser   }
2147b513b491STobias Grosser }
2148b513b491STobias Grosser 
2149f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2150f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2151f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
215279f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
215332837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
215417f01968SSiddharth Bhat 
215517f01968SSiddharth Bhat   switch (Arch) {
215617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
215717f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
215832837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
215917f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
216017f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
216132837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
216217f01968SSiddharth Bhat     break;
21632f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21642f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
21652f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
21662f3073b5SPhilipp Schaad     break;
21672f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21682f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
21692f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
21702f3073b5SPhilipp Schaad     break;
217117f01968SSiddharth Bhat   }
217232837fe3STobias Grosser 
2173edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
217432837fe3STobias Grosser 
217559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
217632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
217732837fe3STobias Grosser 
217859ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
217959ab0705STobias Grosser 
218032837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
218132837fe3STobias Grosser   Builder.CreateRetVoid();
218232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2183472f9654STobias Grosser 
2184629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2185629109b6STobias Grosser 
218600bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2187b513b491STobias Grosser   createKernelVariables(Kernel, FN);
21882f3073b5SPhilipp Schaad 
21892f3073b5SPhilipp Schaad   switch (Arch) {
21902f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2191472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
21922f3073b5SPhilipp Schaad     break;
21932f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21942f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21952f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
21962f3073b5SPhilipp Schaad     break;
21972f3073b5SPhilipp Schaad   }
219832837fe3STobias Grosser }
219932837fe3STobias Grosser 
220074dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
220117f01968SSiddharth Bhat   llvm::Triple GPUTriple;
220217f01968SSiddharth Bhat 
220317f01968SSiddharth Bhat   switch (Arch) {
220417f01968SSiddharth Bhat   case GPUArch::NVPTX64:
220517f01968SSiddharth Bhat     switch (Runtime) {
220617f01968SSiddharth Bhat     case GPURuntime::CUDA:
220717f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
220817f01968SSiddharth Bhat       break;
220917f01968SSiddharth Bhat     case GPURuntime::OpenCL:
221017f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
221117f01968SSiddharth Bhat       break;
221217f01968SSiddharth Bhat     }
221317f01968SSiddharth Bhat     break;
22142f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22152f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22162f3073b5SPhilipp Schaad     std::string SPIRAssembly;
22172f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
22182f3073b5SPhilipp Schaad     IROstream << *GPUModule;
22192f3073b5SPhilipp Schaad     IROstream.flush();
22202f3073b5SPhilipp Schaad     return SPIRAssembly;
222117f01968SSiddharth Bhat   }
222217f01968SSiddharth Bhat 
222374dc3cb4STobias Grosser   std::string ErrMsg;
222474dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
222574dc3cb4STobias Grosser 
222674dc3cb4STobias Grosser   if (!GPUTarget) {
222774dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
222874dc3cb4STobias Grosser     return "";
222974dc3cb4STobias Grosser   }
223074dc3cb4STobias Grosser 
223174dc3cb4STobias Grosser   TargetOptions Options;
223274dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
223317f01968SSiddharth Bhat 
223417f01968SSiddharth Bhat   std::string subtarget;
223517f01968SSiddharth Bhat 
223617f01968SSiddharth Bhat   switch (Arch) {
223717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
223817f01968SSiddharth Bhat     subtarget = CudaVersion;
223917f01968SSiddharth Bhat     break;
22402f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22412f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22422f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
224317f01968SSiddharth Bhat   }
224417f01968SSiddharth Bhat 
224517f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
224617f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
224774dc3cb4STobias Grosser 
224874dc3cb4STobias Grosser   SmallString<0> ASMString;
224974dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
225074dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
225174dc3cb4STobias Grosser 
225274dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
225374dc3cb4STobias Grosser 
225474dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
225574dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
225674dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
225774dc3cb4STobias Grosser     return "";
225874dc3cb4STobias Grosser   }
225974dc3cb4STobias Grosser 
226074dc3cb4STobias Grosser   PM.run(*GPUModule);
226174dc3cb4STobias Grosser 
226274dc3cb4STobias Grosser   return ASMStream.str();
226374dc3cb4STobias Grosser }
226474dc3cb4STobias Grosser 
22658fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
22668fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
22678fc6cdfbSTobias Grosser     if (!F.isDeclaration())
22688fc6cdfbSTobias Grosser       continue;
22698fc6cdfbSTobias Grosser 
22708fc6cdfbSTobias Grosser     std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F);
22718fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
22728fc6cdfbSTobias Grosser       F.setName(CUDALibDeviceFunc);
22738fc6cdfbSTobias Grosser       return true;
22748fc6cdfbSTobias Grosser     }
22758fc6cdfbSTobias Grosser   }
22768fc6cdfbSTobias Grosser 
22778fc6cdfbSTobias Grosser   return false;
22788fc6cdfbSTobias Grosser }
22798fc6cdfbSTobias Grosser 
22808fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
22818fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
22828fc6cdfbSTobias Grosser     return;
22838fc6cdfbSTobias Grosser 
22848fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
22858fc6cdfbSTobias Grosser     SMDiagnostic Error;
22868fc6cdfbSTobias Grosser 
22878fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
22888fc6cdfbSTobias Grosser     auto LibDeviceModule =
22898fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
22908fc6cdfbSTobias Grosser 
22918fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
22928fc6cdfbSTobias Grosser       BuildSuccessful = false;
22938fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
22948fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
22958fc6cdfbSTobias Grosser                          "accordingly.\n");
22968fc6cdfbSTobias Grosser       return;
22978fc6cdfbSTobias Grosser     }
22988fc6cdfbSTobias Grosser 
22998fc6cdfbSTobias Grosser     Linker L(*GPUModule);
23008fc6cdfbSTobias Grosser 
23018fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
23028fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
23038fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
23048fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
23058fc6cdfbSTobias Grosser   }
23068fc6cdfbSTobias Grosser }
23078fc6cdfbSTobias Grosser 
230857793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
230965d7f72fSSiddharth Bhat 
23105857b701STobias Grosser   if (verifyModule(*GPUModule)) {
231165d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
231265d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2313a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2314a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
231565d7f72fSSiddharth Bhat 
231665d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
231765d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
231865d7f72fSSiddharth Bhat 
23195857b701STobias Grosser     BuildSuccessful = false;
23205857b701STobias Grosser     return "";
23215857b701STobias Grosser   }
232232837fe3STobias Grosser 
23238fc6cdfbSTobias Grosser   addCUDALibDevice();
23248fc6cdfbSTobias Grosser 
232532837fe3STobias Grosser   if (DumpKernelIR)
232632837fe3STobias Grosser     outs() << *GPUModule << "\n";
232732837fe3STobias Grosser 
23282f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
23299a18d559STobias Grosser     // Optimize module.
23309a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
23319a18d559STobias Grosser     PassManagerBuilder PassBuilder;
23329a18d559STobias Grosser     PassBuilder.OptLevel = 3;
23339a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
23349a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
23359a18d559STobias Grosser     OptPasses.run(*GPUModule);
23362f3073b5SPhilipp Schaad   }
23379a18d559STobias Grosser 
233874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
233974dc3cb4STobias Grosser 
234074dc3cb4STobias Grosser   if (DumpKernelASM)
234174dc3cb4STobias Grosser     outs() << Assembly << "\n";
234274dc3cb4STobias Grosser 
234332837fe3STobias Grosser   GPUModule.release();
2344472f9654STobias Grosser   KernelIDs.clear();
234557793596STobias Grosser 
234657793596STobias Grosser   return Assembly;
234732837fe3STobias Grosser }
234832837fe3STobias Grosser 
23499dfe4e7cSTobias Grosser namespace {
23509dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
23519dfe4e7cSTobias Grosser public:
23529dfe4e7cSTobias Grosser   static char ID;
23539dfe4e7cSTobias Grosser 
235417f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
235517f01968SSiddharth Bhat 
235617f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
235717f01968SSiddharth Bhat 
2358e938517eSTobias Grosser   /// The scop that is currently processed.
2359e938517eSTobias Grosser   Scop *S;
2360e938517eSTobias Grosser 
236138fc0aedSTobias Grosser   LoopInfo *LI;
236238fc0aedSTobias Grosser   DominatorTree *DT;
236338fc0aedSTobias Grosser   ScalarEvolution *SE;
236438fc0aedSTobias Grosser   const DataLayout *DL;
236538fc0aedSTobias Grosser   RegionInfo *RI;
236638fc0aedSTobias Grosser 
23679dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
23689dfe4e7cSTobias Grosser 
2369e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2370e938517eSTobias Grosser   ///
2371e938517eSTobias Grosser   /// @returns The compilation options.
2372e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2373e938517eSTobias Grosser     auto DebugOptions =
2374e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2375e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2376e938517eSTobias Grosser 
2377e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2378e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2379e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2380e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
23818950ceadSTobias Grosser     DebugOptions->verbose = false;
2382e938517eSTobias Grosser 
2383e938517eSTobias Grosser     Options->debug = DebugOptions;
2384e938517eSTobias Grosser 
23859e3db2b7SSiddharth Bhat     Options->group_chains = false;
2386e938517eSTobias Grosser     Options->reschedule = true;
2387e938517eSTobias Grosser     Options->scale_tile_loops = false;
2388e938517eSTobias Grosser     Options->wrap = false;
2389e938517eSTobias Grosser 
2390e938517eSTobias Grosser     Options->non_negative_parameters = false;
2391e938517eSTobias Grosser     Options->ctx = nullptr;
2392e938517eSTobias Grosser     Options->sizes = nullptr;
2393e938517eSTobias Grosser 
23949e3db2b7SSiddharth Bhat     Options->tile = true;
23954eaedde5STobias Grosser     Options->tile_size = 32;
23964eaedde5STobias Grosser 
23979e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
23989e3db2b7SSiddharth Bhat 
2399130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2400b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2401b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2402e938517eSTobias Grosser 
2403e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2404e938517eSTobias Grosser     Options->openmp = false;
2405e938517eSTobias Grosser     Options->linearize_device_arrays = true;
24069e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2407e938517eSTobias Grosser 
24089e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
24099e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
24109e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24119e3db2b7SSiddharth Bhat 
24129e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
24139e3db2b7SSiddharth Bhat     Options->hybrid = false;
2414e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2415e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2416e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2417e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2418e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2419e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2420e938517eSTobias Grosser 
2421e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2422e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2423e938517eSTobias Grosser 
2424e938517eSTobias Grosser     return Options;
2425e938517eSTobias Grosser   }
2426e938517eSTobias Grosser 
2427f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2428f384594dSTobias Grosser   ///
2429f384594dSTobias Grosser   /// Instead of a normal access of the form:
2430f384594dSTobias Grosser   ///
2431f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2432f384594dSTobias Grosser   ///
2433f384594dSTobias Grosser   /// a tagged access has the form
2434f384594dSTobias Grosser   ///
2435f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2436f384594dSTobias Grosser   ///
2437f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2438f384594dSTobias Grosser   /// triggered the access.
2439f384594dSTobias Grosser   ///
2440f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2441f384594dSTobias Grosser   ///
2442f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2443f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2444f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2445f384594dSTobias Grosser 
2446f384594dSTobias Grosser     for (auto &Stmt : *S)
2447f384594dSTobias Grosser       for (auto &Acc : Stmt)
2448f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
24491515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2450f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2451f384594dSTobias Grosser 
2452f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2453f384594dSTobias Grosser           Space = isl_space_range(Space);
2454f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2455fe46c3ffSTobias Grosser           Space =
2456fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2457f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2458f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2459f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2460f384594dSTobias Grosser         }
2461f384594dSTobias Grosser 
2462f384594dSTobias Grosser     return Accesses;
2463f384594dSTobias Grosser   }
2464f384594dSTobias Grosser 
2465f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2466f384594dSTobias Grosser   ///
2467f384594dSTobias Grosser   /// @see getTaggedAccesses
2468f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2469f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2470f384594dSTobias Grosser   }
2471f384594dSTobias Grosser 
2472f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2473f384594dSTobias Grosser   ///
2474f384594dSTobias Grosser   /// @see getTaggedAccesses
2475f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2476f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2477f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2478f384594dSTobias Grosser   }
2479f384594dSTobias Grosser 
2480f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2481f384594dSTobias Grosser   ///
2482f384594dSTobias Grosser   /// @see getTaggedAccesses
2483f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2484f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2485f384594dSTobias Grosser   }
2486f384594dSTobias Grosser 
2487aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2488aef5196fSTobias Grosser   ///
2489aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2490aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2491aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2492aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2493aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2494aef5196fSTobias Grosser   /// the data format that ppcg expects.
2495aef5196fSTobias Grosser   ///
2496aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2497aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2498aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2499bd81a7eeSTobias Grosser         S->getIslCtx(),
2500bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2501aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2502aef5196fSTobias Grosser 
250325271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
250425271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2505aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2506aef5196fSTobias Grosser     }
2507aef5196fSTobias Grosser 
2508aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
250977eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2510aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2511aef5196fSTobias Grosser     }
2512aef5196fSTobias Grosser 
2513aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2514aef5196fSTobias Grosser 
2515aef5196fSTobias Grosser     return Names;
2516aef5196fSTobias Grosser   }
2517aef5196fSTobias Grosser 
2518e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2519e938517eSTobias Grosser   ///
2520f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2521f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2522f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2523f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2524e938517eSTobias Grosser   ///
2525e938517eSTobias Grosser   /// @returns A new ppcg scop.
2526e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
25279e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
25289e3db2b7SSiddharth Bhat 
2529e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2530e938517eSTobias Grosser 
2531e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2532a82f2d26SSiddharth Bhat     // enable live range reordering
2533a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2534e938517eSTobias Grosser 
2535e938517eSTobias Grosser     PPCGScop->start = 0;
2536e938517eSTobias Grosser     PPCGScop->end = 0;
2537e938517eSTobias Grosser 
2538f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2539f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
25409e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
25419e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2542f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2543f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2544e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2545f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2546f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2547f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2548f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2549e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
25509e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
25519e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
25529e3db2b7SSiddharth Bhat 
2553e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2554a82f2d26SSiddharth Bhat     PPCGScop->independence =
2555a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2556e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2557e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2558e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2559e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2560e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2561e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2562e938517eSTobias Grosser 
2563f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2564a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2565a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2566a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2567a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2568a82f2d26SSiddharth Bhat 
2569a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2570e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2571e938517eSTobias Grosser 
2572f384594dSTobias Grosser     compute_tagger(PPCGScop);
2573f384594dSTobias Grosser     compute_dependences(PPCGScop);
25749e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2575f384594dSTobias Grosser 
2576e938517eSTobias Grosser     return PPCGScop;
2577e938517eSTobias Grosser   }
2578e938517eSTobias Grosser 
2579a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
258060f63b49STobias Grosser   ///
258160f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
258260f63b49STobias Grosser   ///
258360f63b49STobias Grosser   /// @returns A list of array accesses.
258460f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
258560f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
258660f63b49STobias Grosser 
258760f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
258860f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
258960f63b49STobias Grosser       Access->read = Acc->isRead();
259060f63b49STobias Grosser       Access->write = Acc->isWrite();
25911515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
259260f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
259360f63b49STobias Grosser       Space = isl_space_range(Space);
259460f63b49STobias Grosser       Space = isl_space_from_range(Space);
2595fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
259660f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
259760f63b49STobias Grosser       Access->tagged_access =
25981515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2599b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2600fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
260160f63b49STobias Grosser       Access->next = Accesses;
2602b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
260360f63b49STobias Grosser       Accesses = Access;
260460f63b49STobias Grosser     }
260560f63b49STobias Grosser 
260660f63b49STobias Grosser     return Accesses;
260760f63b49STobias Grosser   }
260860f63b49STobias Grosser 
260969b46751STobias Grosser   /// Collect the list of GPU statements.
261069b46751STobias Grosser   ///
261169b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
261269b46751STobias Grosser   /// as well as a list with all memory accesses.
261369b46751STobias Grosser   ///
261469b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
261569b46751STobias Grosser   ///
261669b46751STobias Grosser   /// @returns A linked-list of statements.
261769b46751STobias Grosser   gpu_stmt *getStatements() {
261869b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
261969b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
262069b46751STobias Grosser 
262169b46751STobias Grosser     int i = 0;
262269b46751STobias Grosser     for (auto &Stmt : *S) {
262369b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
262469b46751STobias Grosser 
262569b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
262669b46751STobias Grosser 
262769b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
262869b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
262960f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
263069b46751STobias Grosser       i++;
263169b46751STobias Grosser     }
263269b46751STobias Grosser 
263369b46751STobias Grosser     return Stmts;
263469b46751STobias Grosser   }
263569b46751STobias Grosser 
263660f63b49STobias Grosser   /// Derive the extent of an array.
263760f63b49STobias Grosser   ///
2638d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2639d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2640d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2641d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2642d58acf86STobias Grosser   /// subscript value for the first dimension.
264360f63b49STobias Grosser   ///
264460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
264560f63b49STobias Grosser   ///
264660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
264760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2648d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
264960f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
265060f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2651d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
265260f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2653d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2654d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2655d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2656d58acf86STobias Grosser 
2657d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2658d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
265977eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2660d58acf86STobias Grosser     }
2661d58acf86STobias Grosser 
2662d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2663d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
266477eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2665d58acf86STobias Grosser     }
2666d58acf86STobias Grosser 
266760f63b49STobias Grosser     isl_set *AccessSet =
266877eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
266960f63b49STobias Grosser 
2670d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
267177eef90fSTobias Grosser     isl_local_space *LS =
267277eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2673d58acf86STobias Grosser 
2674d58acf86STobias Grosser     isl_pw_aff *Val =
2675d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2676d58acf86STobias Grosser 
2677d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2678d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2679d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2680d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2681d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2682d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
268377eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
268477eef90fSTobias Grosser                                        Array->getBasePtrId().release());
268577eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
268677eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2687d58acf86STobias Grosser 
268877eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2689d58acf86STobias Grosser 
2690d58acf86STobias Grosser     Extent = isl_set_intersect(
2691d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2692d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2693d58acf86STobias Grosser 
2694d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2695d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2696d58acf86STobias Grosser 
2697b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2698d58acf86STobias Grosser       isl_pw_aff *PwAff =
269977eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2700b7f68b8cSSiddharth Bhat 
2701b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2702b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2703b7f68b8cSSiddharth Bhat       if (!PwAff) {
2704b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2705b7f68b8cSSiddharth Bhat         continue;
2706b7f68b8cSSiddharth Bhat       }
2707b7f68b8cSSiddharth Bhat 
2708d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
270977eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
271077eef90fSTobias Grosser           i));
2711d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2712d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2713d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2714d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2715d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2716d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2717d58acf86STobias Grosser     }
2718d58acf86STobias Grosser 
2719d58acf86STobias Grosser     return Extent;
272060f63b49STobias Grosser   }
272160f63b49STobias Grosser 
272260f63b49STobias Grosser   /// Derive the bounds of an array.
272360f63b49STobias Grosser   ///
272460f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
272560f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
272660f63b49STobias Grosser   /// ScopArrayInfo.
272760f63b49STobias Grosser   ///
272860f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
272960f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
273060f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
27319e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
27329e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
27339e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
27349e3db2b7SSiddharth Bhat 
27359e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
27369e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
27379e3db2b7SSiddharth Bhat 
273860f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
273902293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
274002293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
274102293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
274202293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
274302293ed7STobias Grosser         isl_set_free(Dom);
27449e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
27459e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
27469e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
27479e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
274802293ed7STobias Grosser       } else {
274960f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
275060f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
275160f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
275260f63b49STobias Grosser         isl_set_free(Dom);
275360f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
275402293ed7STobias Grosser         isl_local_space *LS =
275502293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
275660f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
275760f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
275860f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
275960f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
27609e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27619e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27629e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
276360f63b49STobias Grosser       }
276402293ed7STobias Grosser     }
276560f63b49STobias Grosser 
276660f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
276777eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
276860f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
276960f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
277060f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
27719e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
27729e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
27739e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
277460f63b49STobias Grosser     }
27759e3db2b7SSiddharth Bhat 
27769e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
27779e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
27789e3db2b7SSiddharth Bhat 
27799e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
27809e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
27819e3db2b7SSiddharth Bhat 
27829e3db2b7SSiddharth Bhat     PPCGArray.bound =
27839e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
27849e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
278560f63b49STobias Grosser   }
278660f63b49STobias Grosser 
278760f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
278860f63b49STobias Grosser   ///
278960f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
279043f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
279143f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
279260f63b49STobias Grosser     int i = 0;
279343f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
279460f63b49STobias Grosser       std::string TypeName;
279560f63b49STobias Grosser       raw_string_ostream OS(TypeName);
279660f63b49STobias Grosser 
279760f63b49STobias Grosser       OS << *Array->getElementType();
279860f63b49STobias Grosser       TypeName = OS.str();
279960f63b49STobias Grosser 
280060f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
280160f63b49STobias Grosser 
280277eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
280360f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
280460f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
280560f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
280660f63b49STobias Grosser       PPCGArray.extent = nullptr;
280760f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
280860f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
280960f63b49STobias Grosser       PPCGArray.n_ref = 0;
281060f63b49STobias Grosser       PPCGArray.refs = nullptr;
281160f63b49STobias Grosser       PPCGArray.accessed = true;
2812fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2813fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
281460f63b49STobias Grosser       PPCGArray.has_compound_element = false;
281560f63b49STobias Grosser       PPCGArray.local = false;
281660f63b49STobias Grosser       PPCGArray.declare_local = false;
281760f63b49STobias Grosser       PPCGArray.global = false;
281860f63b49STobias Grosser       PPCGArray.linearize = false;
281960f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
282013c78e4dSTobias Grosser       PPCGArray.user = Array;
282160f63b49STobias Grosser 
28229e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
282360f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
28242d010dafSTobias Grosser       i++;
2825b9fc860aSTobias Grosser 
2826b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
282760f63b49STobias Grosser     }
282860f63b49STobias Grosser   }
282960f63b49STobias Grosser 
283060f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
283160f63b49STobias Grosser   ///
283260f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
283360f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
283460f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
283560f63b49STobias Grosser 
2836d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
283777eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
283860f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
283960f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
284060f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
284160f63b49STobias Grosser     }
284260f63b49STobias Grosser 
284360f63b49STobias Grosser     return Maps;
284460f63b49STobias Grosser   }
284560f63b49STobias Grosser 
2846e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2847e938517eSTobias Grosser   ///
2848a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2849e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2850e938517eSTobias Grosser 
2851e938517eSTobias Grosser     if (!PPCGScop)
2852e938517eSTobias Grosser       return nullptr;
2853e938517eSTobias Grosser 
2854e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2855e938517eSTobias Grosser 
2856e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2857e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2858aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
285960f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
286060f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
286160f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
286260f63b49STobias Grosser     PPCGProg->tagged_must_kill =
286360f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
286460f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
286560f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
28669e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2867e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2868a82f2d26SSiddharth Bhat 
2869a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2870a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2871a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2872a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2873a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2874a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
287569b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
287669b46751STobias Grosser     PPCGProg->stmts = getStatements();
287743f178bbSSiddharth Bhat 
287843f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
287943f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
288043f178bbSSiddharth Bhat     // empty arrays:
288143f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
288243f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
288343f178bbSSiddharth Bhat     auto ValidSAIsRange =
288443f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
288543f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
288643f178bbSSiddharth Bhat         });
288743f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
288843f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
288943f178bbSSiddharth Bhat 
289043f178bbSSiddharth Bhat     PPCGProg->n_array =
289143f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
289260f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
289360f63b49STobias Grosser                                        PPCGProg->n_array);
289460f63b49STobias Grosser 
289543f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2896e938517eSTobias Grosser 
2897d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2898e938517eSTobias Grosser     return PPCGProg;
2899e938517eSTobias Grosser   }
2900e938517eSTobias Grosser 
290169b46751STobias Grosser   struct PrintGPUUserData {
290269b46751STobias Grosser     struct cuda_info *CudaInfo;
290369b46751STobias Grosser     struct gpu_prog *PPCGProg;
290469b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
290569b46751STobias Grosser   };
290669b46751STobias Grosser 
290769b46751STobias Grosser   /// Print a user statement node in the host code.
290869b46751STobias Grosser   ///
290969b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
291069b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
291169b46751STobias Grosser   /// host ast.
291269b46751STobias Grosser   ///
291369b46751STobias Grosser   /// @param P The printer to print to
291469b46751STobias Grosser   /// @param Options The printing options to use
291569b46751STobias Grosser   /// @param Node The node to print
291669b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
291769b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
291869b46751STobias Grosser   ///
291969b46751STobias Grosser   /// @returns A printer to which the output has been printed.
292069b46751STobias Grosser   static __isl_give isl_printer *
292169b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
292269b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
292369b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
292469b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
292569b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
292669b46751STobias Grosser 
292769b46751STobias Grosser     if (Id) {
292820251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
292920251734STobias Grosser 
293020251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
293120251734STobias Grosser       // otherwise try to call pet functionality that is not available in
293220251734STobias Grosser       // Polly.
293320251734STobias Grosser       if (IsUser) {
293420251734STobias Grosser         P = isl_printer_start_line(P);
293520251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
293620251734STobias Grosser         P = isl_printer_end_line(P);
293720251734STobias Grosser         isl_id_free(Id);
293820251734STobias Grosser         isl_ast_print_options_free(Options);
293920251734STobias Grosser         return P;
294020251734STobias Grosser       }
294120251734STobias Grosser 
294269b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
294369b46751STobias Grosser       isl_id_free(Id);
294469b46751STobias Grosser       Data->Kernels.push_back(Kernel);
294569b46751STobias Grosser     }
294669b46751STobias Grosser 
294769b46751STobias Grosser     return print_host_user(P, Options, Node, User);
294869b46751STobias Grosser   }
294969b46751STobias Grosser 
295069b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
295169b46751STobias Grosser   ///
295269b46751STobias Grosser   /// @param Kernel The kernel to print
295369b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
295469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
295569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
295669b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
295769b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
295869b46751STobias Grosser     char *String = isl_printer_get_str(P);
295969b46751STobias Grosser     printf("%s\n", String);
296069b46751STobias Grosser     free(String);
296169b46751STobias Grosser     isl_printer_free(P);
296269b46751STobias Grosser   }
296369b46751STobias Grosser 
296469b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
296569b46751STobias Grosser   ///
296669b46751STobias Grosser   /// @param Tree An AST describing GPU code
296769b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
296869b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
296969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
297069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
297169b46751STobias Grosser 
297269b46751STobias Grosser     PrintGPUUserData Data;
297369b46751STobias Grosser     Data.PPCGProg = PPCGProg;
297469b46751STobias Grosser 
297569b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
297669b46751STobias Grosser     Options =
297769b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
297869b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
297969b46751STobias Grosser     char *String = isl_printer_get_str(P);
298069b46751STobias Grosser     printf("# host\n");
298169b46751STobias Grosser     printf("%s\n", String);
298269b46751STobias Grosser     free(String);
298369b46751STobias Grosser     isl_printer_free(P);
298469b46751STobias Grosser 
298569b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
298669b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
298769b46751STobias Grosser       printKernel(Kernel);
298869b46751STobias Grosser     }
298969b46751STobias Grosser   }
299069b46751STobias Grosser 
2991f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2992f384594dSTobias Grosser   //
2993f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2994f384594dSTobias Grosser   //
2995f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2996f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2997f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2998f384594dSTobias Grosser   //
2999f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3000f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3001f384594dSTobias Grosser   // strategy directly from this pass.
3002f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3003f384594dSTobias Grosser 
3004f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
3005f384594dSTobias Grosser 
3006f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
3007f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3008f384594dSTobias Grosser     PPCGGen->print = nullptr;
3009f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
301060c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3011f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3012f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3013f384594dSTobias Grosser     PPCGGen->types.n = 0;
3014f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3015f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3016f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3017f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3018f384594dSTobias Grosser 
3019f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3020f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3021f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
30222341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3023f384594dSTobias Grosser 
3024f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3025f384594dSTobias Grosser 
3026aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3027aef5196fSTobias Grosser 
302869b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3029aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
303069b46751STobias Grosser     } else {
3031aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
303269b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
303369b46751STobias Grosser     }
3034aef5196fSTobias Grosser 
3035f384594dSTobias Grosser     if (DumpSchedule) {
3036f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
3037f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3038f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3039f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3040f384594dSTobias Grosser       if (Schedule)
3041f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3042f384594dSTobias Grosser       else
3043f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3044f384594dSTobias Grosser 
3045f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
3046f384594dSTobias Grosser       isl_printer_free(P);
3047f384594dSTobias Grosser     }
3048f384594dSTobias Grosser 
304969b46751STobias Grosser     if (DumpCode) {
305069b46751STobias Grosser       printf("Code\n");
305169b46751STobias Grosser       printf("====\n");
305269b46751STobias Grosser       if (PPCGGen->tree)
305369b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
305469b46751STobias Grosser       else
305569b46751STobias Grosser         printf("No code generated\n");
305669b46751STobias Grosser     }
305769b46751STobias Grosser 
3058f384594dSTobias Grosser     isl_schedule_free(Schedule);
3059f384594dSTobias Grosser 
3060f384594dSTobias Grosser     return PPCGGen;
3061f384594dSTobias Grosser   }
3062f384594dSTobias Grosser 
3063f384594dSTobias Grosser   /// Free gpu_gen structure.
3064f384594dSTobias Grosser   ///
3065f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3066f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3067f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3068f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3069f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3070f384594dSTobias Grosser     free(PPCGGen);
3071f384594dSTobias Grosser   }
3072f384594dSTobias Grosser 
3073b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3074b307ed4dSTobias Grosser   ///
3075b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3076b307ed4dSTobias Grosser   /// ourselves.
3077b307ed4dSTobias Grosser   ///
3078b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3079b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3080b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3081b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3082b307ed4dSTobias Grosser     free(PPCGScop->options);
3083b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3084b307ed4dSTobias Grosser   }
3085b307ed4dSTobias Grosser 
308682f2af35STobias Grosser   /// Approximate the number of points in the set.
308782f2af35STobias Grosser   ///
308882f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
308982f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
309082f2af35STobias Grosser   ///
309182f2af35STobias Grosser   /// @param Set   The set to count.
309282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
309382f2af35STobias Grosser   ///              expression.
309482f2af35STobias Grosser   ///
309582f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
309682f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
309782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
309882f2af35STobias Grosser 
309982f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
310082f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
310182f2af35STobias Grosser 
310282f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
310382f2af35STobias Grosser     Space = isl_space_params(Space);
310482f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
310582f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
310682f2af35STobias Grosser 
310782f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
310882f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
310982f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
311082f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
311182f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
311282f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
311382f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
311482f2af35STobias Grosser     }
311582f2af35STobias Grosser 
311682f2af35STobias Grosser     isl_set_free(Set);
311782f2af35STobias Grosser     isl_pw_aff_free(OneAff);
311882f2af35STobias Grosser 
311982f2af35STobias Grosser     return Expr;
312082f2af35STobias Grosser   }
312182f2af35STobias Grosser 
312282f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
312382f2af35STobias Grosser   /// statement.
312482f2af35STobias Grosser   ///
312582f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
312682f2af35STobias Grosser   ///              instructions.
312782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
312882f2af35STobias Grosser   ///              expression.
312982f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
313082f2af35STobias Grosser   ///          by @p Stmt.
313182f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
313282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
313382f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
313482f2af35STobias Grosser 
313582f2af35STobias Grosser     long InstCount = 0;
313682f2af35STobias Grosser 
313782f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
313882f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
313982f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
314082f2af35STobias Grosser     } else {
314182f2af35STobias Grosser       auto *R = Stmt.getRegion();
314282f2af35STobias Grosser 
314382f2af35STobias Grosser       for (auto *BB : R->blocks()) {
314482f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
314582f2af35STobias Grosser       }
314682f2af35STobias Grosser     }
314782f2af35STobias Grosser 
314882f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
314982f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
315082f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
315182f2af35STobias Grosser   }
315282f2af35STobias Grosser 
315382f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
315482f2af35STobias Grosser   ///
315582f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
315682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
315782f2af35STobias Grosser   ///              expression.
315882f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
315982f2af35STobias Grosser   ///          in @p S.
316082f2af35STobias Grosser   __isl_give isl_ast_expr *
316182f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
316282f2af35STobias Grosser     isl_ast_expr *Instructions;
316382f2af35STobias Grosser 
316482f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
316582f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
316682f2af35STobias Grosser 
316782f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
316882f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
316982f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
317082f2af35STobias Grosser     }
317182f2af35STobias Grosser     return Instructions;
317282f2af35STobias Grosser   }
317382f2af35STobias Grosser 
317482f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
317582f2af35STobias Grosser   ///
317682f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
317782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
317882f2af35STobias Grosser   ///              expression.
317982f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
318082f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
318182f2af35STobias Grosser   __isl_give isl_ast_expr *
318282f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
318382f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
318482f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
318582f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
318682f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
318782f2af35STobias Grosser   }
318882f2af35STobias Grosser 
3189f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3190f291c8d5SSiddharth Bhat   /// kernels.
3191f291c8d5SSiddharth Bhat   ///
3192f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3193f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
31948fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
31958fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3196f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3197f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
31988fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
31998fc6cdfbSTobias Grosser                                           AllowCUDALibDevice)) {
3200f291c8d5SSiddharth Bhat         continue;
3201f291c8d5SSiddharth Bhat       }
3202f291c8d5SSiddharth Bhat 
3203bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3204bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3205bccaea57SSiddharth Bhat         if (!p)
3206bccaea57SSiddharth Bhat           continue;
3207bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3208bccaea57SSiddharth Bhat           return true;
3209bccaea57SSiddharth Bhat       }
3210f291c8d5SSiddharth Bhat     }
3211bccaea57SSiddharth Bhat     return false;
3212bccaea57SSiddharth Bhat   }
3213bccaea57SSiddharth Bhat 
3214f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
32158fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3216bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3217bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
32188fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
32198fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3220bccaea57SSiddharth Bhat           return true;
3221bccaea57SSiddharth Bhat       } else {
3222bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3223bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3224bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
32258fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3226bccaea57SSiddharth Bhat             return true;
3227bccaea57SSiddharth Bhat       }
3228bccaea57SSiddharth Bhat     }
3229bccaea57SSiddharth Bhat     return false;
3230bccaea57SSiddharth Bhat   }
3231bccaea57SSiddharth Bhat 
323238fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
323338fc0aedSTobias Grosser   ///
323432837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
323532837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
323632837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
323738fc0aedSTobias Grosser     ScopAnnotator Annotator;
323838fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
323938fc0aedSTobias Grosser 
324038fc0aedSTobias Grosser     Region *R = &S->getRegion();
324138fc0aedSTobias Grosser 
324238fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
324338fc0aedSTobias Grosser 
324438fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
324538fc0aedSTobias Grosser 
324638fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
324738fc0aedSTobias Grosser 
324838fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
324938fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
325038fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
325138fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
325238fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
325338fc0aedSTobias Grosser     // code generating this scop.
325403346c27SSiddharth Bhat     BBPair StartExitBlocks;
325503346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
325603346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
32572d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3258256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
325938fc0aedSTobias Grosser 
326003346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
326103346c27SSiddharth Bhat 
32622d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
326317f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3264acf80064SEli Friedman 
326538fc0aedSTobias Grosser     // TODO: Handle LICM
326638fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
326738fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
326838fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3269cb1aef8dSTobias Grosser 
3270cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
32712b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
327282f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
327382f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3274cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3275cb1aef8dSTobias Grosser 
32769e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
32779e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
32784ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
32794ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
32804ebeb356SSiddharth Bhat                          S->getFunction().getName() +
32814ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
32829e3db2b7SSiddharth Bhat 
3283cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3284cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3285cb1aef8dSTobias Grosser 
328638fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3287fa7b0802STobias Grosser 
328838fc0aedSTobias Grosser     NodeBuilder.create(Root);
32895857b701STobias Grosser 
3290bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3291bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3292de244eb4STobias Grosser     /// point in running it on a GPU.
3293bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
329403346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3295bc653f20STobias Grosser 
32965857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
329703346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
329838fc0aedSTobias Grosser   }
329938fc0aedSTobias Grosser 
3300e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3301e938517eSTobias Grosser     S = &CurrentScop;
330238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
330338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
330438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
33057b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
330638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3307e938517eSTobias Grosser 
3308f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3309f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3310f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3311bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3312bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
33138fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
33148fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3315f291c8d5SSiddharth Bhat       DEBUG(
3316f291c8d5SSiddharth Bhat           dbgs()
3317f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3318f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3319bccaea57SSiddharth Bhat       return false;
3320f291c8d5SSiddharth Bhat     }
3321bccaea57SSiddharth Bhat 
3322e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3323e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3324f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
332538fc0aedSTobias Grosser 
332602ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
332732837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
332802ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
332902ca346eSSingapuram Sanjay Srivallabh     }
333038fc0aedSTobias Grosser 
3331b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3332f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3333e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3334e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3335e938517eSTobias Grosser 
3336e938517eSTobias Grosser     return true;
3337e938517eSTobias Grosser   }
33389dfe4e7cSTobias Grosser 
33399dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
33409dfe4e7cSTobias Grosser 
33419dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
33429dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
33439dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
33449dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
33455cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
33469dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
33479dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
33489dfe4e7cSTobias Grosser 
33499dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
33509dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
33519dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
33529dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
33539dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
33545cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
33559dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
33569dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
33579dfe4e7cSTobias Grosser 
33589dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
33599dfe4e7cSTobias Grosser     //        region tree.
33609dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
33619dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
33629dfe4e7cSTobias Grosser   }
33639dfe4e7cSTobias Grosser };
336424222c73STobias Grosser } // namespace
33659dfe4e7cSTobias Grosser 
33669dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
33679dfe4e7cSTobias Grosser 
336817f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
336917f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
337017f01968SSiddharth Bhat   generator->Runtime = Runtime;
337117f01968SSiddharth Bhat   generator->Architecture = Arch;
337217f01968SSiddharth Bhat   return generator;
337317f01968SSiddharth Bhat }
33749dfe4e7cSTobias Grosser 
33759dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
33769dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
33779dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
33789dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
33799dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
33809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
33819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
33825cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
33839dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
33849dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3385