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"
1671dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h"
17cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
189dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
197b9f5ca2SSiddharth Bhat #include "polly/CodeGen/PerfMonitor.h"
2038fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
219dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
229dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
23f384594dSTobias Grosser #include "polly/Options.h"
24629109b6STobias Grosser #include "polly/ScopDetection.h"
259dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
26edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2774dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
309dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
319dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3274dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3374dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3474dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
35e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
368fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h"
378fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h"
3874dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3974dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
4074dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
419a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
42750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
439dfe4e7cSTobias Grosser 
44f384594dSTobias Grosser #include "isl/union_map.h"
45f384594dSTobias Grosser 
46e938517eSTobias Grosser extern "C" {
47a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
48a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
49a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
50a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
51a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
52e938517eSTobias Grosser }
53e938517eSTobias Grosser 
549dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
559dfe4e7cSTobias Grosser 
569dfe4e7cSTobias Grosser using namespace polly;
579dfe4e7cSTobias Grosser using namespace llvm;
589dfe4e7cSTobias Grosser 
599dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
609dfe4e7cSTobias Grosser 
61f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
62f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
63681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
64f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6569b46751STobias Grosser 
6669b46751STobias Grosser static cl::opt<bool>
6769b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6869b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6969b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
7069b46751STobias Grosser 
7132837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
7232837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
7332837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7432837fe3STobias Grosser                                   cl::cat(PollyCategory));
7532837fe3STobias Grosser 
7674dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7774dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7874dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7974dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
8074dc3cb4STobias Grosser 
8174dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
8274dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
8374dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8474dc3cb4STobias Grosser                               cl::cat(PollyCategory));
85b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
86b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
87b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
88b513b491STobias Grosser                                   cl::cat(PollyCategory));
89130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
90130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
91130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
92130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
9374dc3cb4STobias Grosser 
94c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory;
95c4a4af47SSiddharth Bhat static cl::opt<bool, true>
96c4a4af47SSiddharth Bhat     XManagedMemory("polly-acc-codegen-managed-memory",
97abed4969SSiddharth Bhat                    cl::desc("Generate Host kernel code assuming"
98abed4969SSiddharth Bhat                             " that all memory has been"
99abed4969SSiddharth Bhat                             " declared as managed memory"),
100c4a4af47SSiddharth Bhat                    cl::location(PollyManagedMemory), cl::Hidden,
101c4a4af47SSiddharth Bhat                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
102abed4969SSiddharth Bhat 
10365d7f72fSSiddharth Bhat static cl::opt<bool>
10465d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
10565d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10665d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10765d7f72fSSiddharth Bhat                                        " kernel module."),
10865d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10965d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
11065d7f72fSSiddharth Bhat 
1118fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice(
1128fc6cdfbSTobias Grosser     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
1138fc6cdfbSTobias Grosser     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
1148fc6cdfbSTobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
1158fc6cdfbSTobias Grosser 
11674dc3cb4STobias Grosser static cl::opt<std::string>
11774dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
11874dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
11974dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
12074dc3cb4STobias Grosser 
12182f2af35STobias Grosser static cl::opt<int>
12282f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
12382f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
12482f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
12582f2af35STobias Grosser 
1267b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring;
1277b9f5ca2SSiddharth Bhat 
128638316daSSiddharth Bhat /// Return  a unique name for a Scop, which is the scop region with the
129638316daSSiddharth Bhat /// function name.
130638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) {
131638316daSSiddharth Bhat   return "Scop Region: " + S->getNameStr() +
132638316daSSiddharth Bhat          " | Function: " + std::string(S->getFunction().getName());
133638316daSSiddharth Bhat }
134638316daSSiddharth Bhat 
135a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
136a82f2d26SSiddharth Bhat /// used by live range reordering.
137a82f2d26SSiddharth Bhat ///
138a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
139a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
140a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
141a82f2d26SSiddharth Bhat struct MustKillsInfo {
142a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
143a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
144a82f2d26SSiddharth Bhat   ///
145a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
146a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
147a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
148a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
149a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
150a82f2d26SSiddharth Bhat   /// killed.
151a82f2d26SSiddharth Bhat   ///
152edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
153edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
154edfef5aeSSiddharth Bhat   ///     consequently all be killed.
155edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
156edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
157edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
158a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
159a82f2d26SSiddharth Bhat 
1609e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1619e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1629e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1639e3db2b7SSiddharth Bhat 
1649e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
165a82f2d26SSiddharth Bhat };
166a82f2d26SSiddharth Bhat 
167761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
168761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
169761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
170761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
171761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
172761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
173761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
174761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
175761e5b93SSiddharth Bhat 
176761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
177761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
178761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
179761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
180761e5b93SSiddharth Bhat     if (!R.contains(I))
181761e5b93SSiddharth Bhat       return false;
182761e5b93SSiddharth Bhat   }
183761e5b93SSiddharth Bhat   return true;
184761e5b93SSiddharth Bhat }
185761e5b93SSiddharth Bhat 
186a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
187a82f2d26SSiddharth Bhat ///
188a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
189a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
190a82f2d26SSiddharth Bhat /// PPCG.
191a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
192b65ccc43STobias Grosser   const isl::space ParamSpace = S.getParamSpace();
193a82f2d26SSiddharth Bhat   MustKillsInfo Info;
194a82f2d26SSiddharth Bhat 
195761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
196761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
197761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
198a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
199a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
200761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
201761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
20277eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
203a82f2d26SSiddharth Bhat   }
204a82f2d26SSiddharth Bhat 
205d70ea7feSTobias Grosser   Info.TaggedMustKills = isl::union_map::empty(ParamSpace);
206d70ea7feSTobias Grosser   Info.MustKills = isl::union_map::empty(ParamSpace);
207a82f2d26SSiddharth Bhat 
208a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
209a82f2d26SSiddharth Bhat   // schedule:
210a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
211a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
212a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
213a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
214a82f2d26SSiddharth Bhat 
215edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
216a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
217edfef5aeSSiddharth Bhat         S.getIslCtx(),
218edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
219a82f2d26SSiddharth Bhat 
220a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
221a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
222edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
223a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
224edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
225edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
226edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
227edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
228a82f2d26SSiddharth Bhat     //
229a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
230a82f2d26SSiddharth Bhat     // TaggedMustKill:
231edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
232a82f2d26SSiddharth Bhat 
233edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
234d70ea7feSTobias Grosser     isl::map StmtToScalar = isl::map::universe(ParamSpace);
235edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
236edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
237a82f2d26SSiddharth Bhat 
238a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
239edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
240edfef5aeSSiddharth Bhat         nullptr);
241a82f2d26SSiddharth Bhat 
242edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
243d70ea7feSTobias Grosser     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
244edfef5aeSSiddharth Bhat     PhantomRefToScalar =
245edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
246edfef5aeSSiddharth Bhat     PhantomRefToScalar =
247edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
248a82f2d26SSiddharth Bhat 
249edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
250edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
251a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
252a82f2d26SSiddharth Bhat 
2539e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2549e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2559e3db2b7SSiddharth Bhat 
256a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
257a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
258a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
259a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
260a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
261a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
262a82f2d26SSiddharth Bhat 
263a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
264a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
265*5f865032STobias Grosser       Info.KillsSchedule = isl::manage(
266*5f865032STobias Grosser           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
267a82f2d26SSiddharth Bhat     else
268a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
269a82f2d26SSiddharth Bhat   }
270a82f2d26SSiddharth Bhat 
271a82f2d26SSiddharth Bhat   return Info;
272a82f2d26SSiddharth Bhat }
273a82f2d26SSiddharth Bhat 
27460c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
27560c60025STobias Grosser ///
27660c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
27760c60025STobias Grosser /// of the scheduled ScopStmts.
27860c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
27935de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
28060c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
28160c60025STobias Grosser                                        isl_id *Id, void *User),
28260c60025STobias Grosser     void *UserIndex,
28360c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
284edb885cbSTobias Grosser     void *UserExpr) {
28560c60025STobias Grosser 
286edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
28760c60025STobias Grosser 
28835de9009SSiddharth Bhat   if (!Stmt || !Build_C)
289edb885cbSTobias Grosser     return NULL;
290edb885cbSTobias Grosser 
291718d04c6STobias Grosser   isl::ast_build Build = isl::manage_copy(Build_C);
29235de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
29335de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
294edb885cbSTobias Grosser 
295cff9696eSTobias Grosser   Stmt->setAstBuild(Build);
296cff9696eSTobias Grosser 
297edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
29835de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
299dcf8d696STobias Grosser     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
30035de9009SSiddharth Bhat 
30135de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
30235de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
30335de9009SSiddharth Bhat 
30435de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
30535de9009SSiddharth Bhat     MPA = MPA.coalesce();
30635de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
30735de9009SSiddharth Bhat 
30835de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
30935de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
31035de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
311edb885cbSTobias Grosser   }
312edb885cbSTobias Grosser 
31335de9009SSiddharth Bhat   return RefToExpr.release();
31460c60025STobias Grosser }
315f384594dSTobias Grosser 
316a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
317a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
318a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
319a90be207SSiddharth Bhat   if (bytes == 0)
320a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
321a90be207SSiddharth Bhat   return bytes;
322a90be207SSiddharth Bhat }
323a90be207SSiddharth Bhat 
32438fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
32538fc0aedSTobias Grosser ///
32638fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
327a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
32838fc0aedSTobias Grosser /// for generating GPU specific user nodes.
32938fc0aedSTobias Grosser ///
33038fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
33138fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
33238fc0aedSTobias Grosser public:
3332d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
33438fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
335acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
33617f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3372d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
33817f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
339edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
340edb885cbSTobias Grosser   }
34138fc0aedSTobias Grosser 
342fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
343fa7b0802STobias Grosser   void initializeAfterRTH();
344fa7b0802STobias Grosser 
345fa7b0802STobias Grosser   /// Finalize the generated scop.
346fa7b0802STobias Grosser   virtual void finalize();
347fa7b0802STobias Grosser 
3485857b701STobias Grosser   /// Track if the full build process was successful.
3495857b701STobias Grosser   ///
3505857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3515857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3525857b701STobias Grosser   bool BuildSuccessful = true;
3535857b701STobias Grosser 
354bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
355bc653f20STobias Grosser   unsigned DeepestSequential = 0;
356bc653f20STobias Grosser 
357bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
358bc653f20STobias Grosser   unsigned DeepestParallel = 0;
359bc653f20STobias Grosser 
36079f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
36179f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
36279f13b9aSSingapuram Sanjay Srivallabh 
36338fc0aedSTobias Grosser private:
36474dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
36574dc3cb4STobias Grosser   ///
36674dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
36774dc3cb4STobias Grosser   /// more.
36874dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
36974dc3cb4STobias Grosser 
37013c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
37113c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3727287aeddSTobias Grosser 
373fa7b0802STobias Grosser   /// The current GPU context.
374fa7b0802STobias Grosser   Value *GPUContext;
375fa7b0802STobias Grosser 
376b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
377b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
378b513b491STobias Grosser 
37932837fe3STobias Grosser   /// A module containing GPU code.
38032837fe3STobias Grosser   ///
38132837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
38232837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
38332837fe3STobias Grosser 
38432837fe3STobias Grosser   /// The GPU program we generate code for.
38532837fe3STobias Grosser   gpu_prog *Prog;
38632837fe3STobias Grosser 
38717f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
38817f01968SSiddharth Bhat   GPURuntime Runtime;
38917f01968SSiddharth Bhat 
39017f01968SSiddharth Bhat   /// The GPU Architecture to target.
39117f01968SSiddharth Bhat   GPUArch Arch;
39217f01968SSiddharth Bhat 
393472f9654STobias Grosser   /// Class to free isl_ids.
394472f9654STobias Grosser   class IslIdDeleter {
395472f9654STobias Grosser   public:
396472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
397472f9654STobias Grosser   };
398472f9654STobias Grosser 
399472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
400472f9654STobias Grosser   ///
401472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
402472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
403472f9654STobias Grosser 
404edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
405edb885cbSTobias Grosser 
40638fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
40738fc0aedSTobias Grosser   ///
40838fc0aedSTobias Grosser   /// These AST nodes can be of type:
40938fc0aedSTobias Grosser   ///
41038fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
41138fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
41213c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
4135260c041STobias Grosser   ///   - In-kernel synchronization
4145260c041STobias Grosser   ///   - In-kernel memory copy statement
41538fc0aedSTobias Grosser   ///
4161fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
4171fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
41832837fe3STobias Grosser 
41953c80387SPhilip Pfaffe   virtual void createFor(__isl_take isl_ast_node *Node);
42053c80387SPhilip Pfaffe 
42113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
42213c78e4dSTobias Grosser 
42313c78e4dSTobias Grosser   /// Create code for a data transfer statement
42413c78e4dSTobias Grosser   ///
42513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
42613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
42713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
42813c78e4dSTobias Grosser                           enum DataDirection Direction);
42913c78e4dSTobias Grosser 
430edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
431edb885cbSTobias Grosser   ///
432edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
433edb885cbSTobias Grosser   ///
434e53c924bSSiddharth Bhat   /// @returns A tuple, whose:
435e53c924bSSiddharth Bhat   ///          - First element contains the set of values referenced by the
436e53c924bSSiddharth Bhat   ///            kernel
437e53c924bSSiddharth Bhat   ///          - Second element contains the set of functions referenced by the
438e53c924bSSiddharth Bhat   ///             kernel. All functions in the set satisfy
439e53c924bSSiddharth Bhat   ///             `isValidFunctionInKernel`.
440e53c924bSSiddharth Bhat   ///          - Third element contains loops that have induction variables
441e53c924bSSiddharth Bhat   ///            which are used in the kernel, *and* these loops are *neither*
442e53c924bSSiddharth Bhat   ///            in the scop, nor do they immediately surroung the Scop.
443e53c924bSSiddharth Bhat   ///            See [Code generation of induction variables of loops outside
444e53c924bSSiddharth Bhat   ///            Scops]
44543df2020STobias Grosser   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
44643df2020STobias Grosser              isl::space>
447f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
448edb885cbSTobias Grosser 
44979a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
45079a947c2STobias Grosser   ///
45179a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
45279a947c2STobias Grosser   ///
45379a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
45479a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
45579a947c2STobias Grosser 
456b99c1171STobias Grosser   /// Get the managed array pointer for sending host pointers to the device.
457abed4969SSiddharth Bhat   /// \note
458abed4969SSiddharth Bhat   /// This is to be used only with managed memory
459b99c1171STobias Grosser   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
460abed4969SSiddharth Bhat 
46179a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
46279a947c2STobias Grosser   ///
46379a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
46479a947c2STobias Grosser   ///
46579a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
46679a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
46779a947c2STobias Grosser 
468a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
469a90be207SSiddharth Bhat   /// parameters.
470a90be207SSiddharth Bhat   ///
471a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
472a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
473a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
474a90be207SSiddharth Bhat   ///                   parameter.
475a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
476a90be207SSiddharth Bhat                             int Index);
477a90be207SSiddharth Bhat 
47879a947c2STobias Grosser   /// Create kernel launch parameters.
47979a947c2STobias Grosser   ///
48079a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
48179a947c2STobias Grosser   /// @param F             The kernel function that has been created.
48257693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
48379a947c2STobias Grosser   ///
48479a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
48579a947c2STobias Grosser   ///          values that are passed to the kernel.
48657693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
48757693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
48879a947c2STobias Grosser 
489b513b491STobias Grosser   /// Create declarations for kernel variable.
490b513b491STobias Grosser   ///
491b513b491STobias Grosser   /// This includes shared memory declarations.
492b513b491STobias Grosser   ///
493b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
494b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
495b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
496b513b491STobias Grosser 
497c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
498c1c6a2a6STobias Grosser   ///
499c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
500c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
501c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
502c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
503c1c6a2a6STobias Grosser   /// as specified here.
504c1c6a2a6STobias Grosser   ///
505c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
506c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
507c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
508c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
509c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
510c1c6a2a6STobias Grosser                           Value *BlockDimZ);
511c1c6a2a6STobias Grosser 
51232837fe3STobias Grosser   /// Create GPU kernel.
51332837fe3STobias Grosser   ///
51432837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
51532837fe3STobias Grosser   ///
51632837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
51732837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
51832837fe3STobias Grosser 
51913c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
52013c78e4dSTobias Grosser   ///
52113c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
52213c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
52313c78e4dSTobias Grosser 
524aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
525aaabbbf8STobias Grosser   ///
526aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
527aaabbbf8STobias Grosser   ///
528aaabbbf8STobias Grosser   /// Example:
529aaabbbf8STobias Grosser   ///
530aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
531aaabbbf8STobias Grosser   ///     A[i + 42] += ...
532aaabbbf8STobias Grosser   ///
533aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
534aaabbbf8STobias Grosser   ///
535aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
536aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
537aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
538aaabbbf8STobias Grosser 
53900bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
54000bb5a99STobias Grosser   ///
54100bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
54200bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
54300bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
54400bb5a99STobias Grosser 
54532837fe3STobias Grosser   /// Create kernel function.
54632837fe3STobias Grosser   ///
54732837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
54832837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
54932837fe3STobias Grosser   /// start block of this newly created function.
55032837fe3STobias Grosser   ///
55132837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
552edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
553f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
554f291c8d5SSiddharth Bhat   ///                         kernel.
555edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
556f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
557f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
55832837fe3STobias Grosser 
55932837fe3STobias Grosser   /// Create the declaration of a kernel function.
56032837fe3STobias Grosser   ///
56132837fe3STobias Grosser   /// The kernel function takes as arguments:
56232837fe3STobias Grosser   ///
56332837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
564f6044bd0STobias Grosser   ///   - Host iterators
565c84a1995STobias Grosser   ///   - Parameters
56632837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
56732837fe3STobias Grosser   ///
56832837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
569edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
570edb885cbSTobias Grosser   ///
57132837fe3STobias Grosser   /// @returns The newly declared function.
572edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
573edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
57432837fe3STobias Grosser 
575472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
576472f9654STobias Grosser   ///
577472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
578472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
579472f9654STobias Grosser 
5802f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5812f3073b5SPhilipp Schaad   ///
582d71493cbSPhilip Pfaffe   /// @param Kernel The kernel to generate the function calls for.
583d71493cbSPhilip Pfaffe   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
584d71493cbSPhilip Pfaffe   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
5852f3073b5SPhilipp Schaad 
586f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
587f291c8d5SSiddharth Bhat   ///
588f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
589f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
590f291c8d5SSiddharth Bhat   ///
591f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
592f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
593f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
594f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
595f291c8d5SSiddharth Bhat   ///
596f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
597f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
598f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
599f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
600f291c8d5SSiddharth Bhat   ///
601f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
602f291c8d5SSiddharth Bhat   ///                         this kernel.
603f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
604f291c8d5SSiddharth Bhat 
605b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
606b513b491STobias Grosser   ///
607b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
608b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
609b513b491STobias Grosser 
610edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
611edb885cbSTobias Grosser   ///
612edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
613edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
614edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
615edb885cbSTobias Grosser 
6165260c041STobias Grosser   /// Create an in-kernel synchronization call.
6175260c041STobias Grosser   void createKernelSync();
6185260c041STobias Grosser 
61974dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
62074dc3cb4STobias Grosser   ///
62174dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
62274dc3cb4STobias Grosser   std::string createKernelASM();
62374dc3cb4STobias Grosser 
62474dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
62574dc3cb4STobias Grosser   ///
62674dc3cb4STobias Grosser   /// @param F The function to remove references to.
62774dc3cb4STobias Grosser   void clearDominators(Function *F);
62874dc3cb4STobias Grosser 
62974dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
63074dc3cb4STobias Grosser   ///
63174dc3cb4STobias Grosser   /// @param F The function to remove references to.
63274dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
63374dc3cb4STobias Grosser 
63474dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
63574dc3cb4STobias Grosser   ///
63674dc3cb4STobias Grosser   /// @param F The function to remove references to.
63774dc3cb4STobias Grosser   void clearLoops(Function *F);
63874dc3cb4STobias Grosser 
6398fc6cdfbSTobias Grosser   /// Check if the scop requires to be linked with CUDA's libdevice.
6408fc6cdfbSTobias Grosser   bool requiresCUDALibDevice();
6418fc6cdfbSTobias Grosser 
6428fc6cdfbSTobias Grosser   /// Link with the NVIDIA libdevice library (if needed and available).
6438fc6cdfbSTobias Grosser   void addCUDALibDevice();
6448fc6cdfbSTobias Grosser 
64532837fe3STobias Grosser   /// Finalize the generation of the kernel function.
64632837fe3STobias Grosser   ///
64732837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
64832837fe3STobias Grosser   /// dump its IR to stderr.
64957793596STobias Grosser   ///
65057793596STobias Grosser   /// @returns The Assembly string of the kernel.
65157793596STobias Grosser   std::string finalizeKernelFunction();
652fa7b0802STobias Grosser 
65351dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
65451dfc275STobias Grosser   ///
65551dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
656a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
65751dfc275STobias Grosser   /// the kernel terminates.
65851dfc275STobias Grosser   ///
65951dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
66051dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
66151dfc275STobias Grosser 
6627287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
663fa7b0802STobias Grosser   void allocateDeviceArrays();
664fa7b0802STobias Grosser 
665b99c1171STobias Grosser   /// Create code to prepare the managed device pointers.
666b99c1171STobias Grosser   void prepareManagedDeviceArrays();
667b99c1171STobias Grosser 
6687287aeddSTobias Grosser   /// Free all allocated device arrays.
6697287aeddSTobias Grosser   void freeDeviceArrays();
6707287aeddSTobias Grosser 
671fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
672fa7b0802STobias Grosser   ///
673fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
674fa7b0802STobias Grosser   Value *createCallInitContext();
675fa7b0802STobias Grosser 
67679a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
67779a947c2STobias Grosser   ///
67879a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
67979a947c2STobias Grosser   ///
68079a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
68179a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
68279a947c2STobias Grosser 
683fa7b0802STobias Grosser   /// Create a call to free the GPU context.
684fa7b0802STobias Grosser   ///
685fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
686fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
687fa7b0802STobias Grosser 
6887287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6897287aeddSTobias Grosser   ///
6907287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6917287aeddSTobias Grosser   ///
6927287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
693fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6947287aeddSTobias Grosser 
6957287aeddSTobias Grosser   /// Create a call to free a device array.
6967287aeddSTobias Grosser   ///
6977287aeddSTobias Grosser   /// @param Array The device array to free.
6987287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
69913c78e4dSTobias Grosser 
70013c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
70113c78e4dSTobias Grosser   ///
70213c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
70313c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
70413c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
70513c78e4dSTobias Grosser                                       Value *Size);
70613c78e4dSTobias Grosser 
70713c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
70813c78e4dSTobias Grosser   ///
70913c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
71013c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
71113c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
71213c78e4dSTobias Grosser                                       Value *Size);
71357793596STobias Grosser 
714abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
715abed4969SSiddharth Bhat   /// \note
716abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
717abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
718abed4969SSiddharth Bhat 
71957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
72057793596STobias Grosser   ///
72157793596STobias Grosser   /// @param Buffer The string describing the kernel.
72257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
72357793596STobias Grosser   ///
72457793596STobias Grosser   /// @returns A pointer to a kernel object
72557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
72657793596STobias Grosser 
72757793596STobias Grosser   /// Create a call to free a GPU kernel.
72857793596STobias Grosser   ///
72957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
73057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
73179a947c2STobias Grosser 
73279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
73379a947c2STobias Grosser   ///
73479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
73579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
73679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
73779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
73879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
73979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
740a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
74179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
74279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
74379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
74479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
74579a947c2STobias Grosser                               Value *Parameters);
7461fb9b64dSTobias Grosser };
7471fb9b64dSTobias Grosser 
74879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7491abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7501abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
75179f13b9aSSingapuram Sanjay Srivallabh }
75279f13b9aSSingapuram Sanjay Srivallabh 
753fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
754750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
755750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
756750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
757750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
758750160e2STobias Grosser 
759fa7b0802STobias Grosser   GPUContext = createCallInitContext();
760abed4969SSiddharth Bhat 
761c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
762fa7b0802STobias Grosser     allocateDeviceArrays();
763b99c1171STobias Grosser   else
764b99c1171STobias Grosser     prepareManagedDeviceArrays();
765fa7b0802STobias Grosser }
766fa7b0802STobias Grosser 
767fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
768c4a4af47SSiddharth Bhat   if (!PollyManagedMemory)
7697287aeddSTobias Grosser     freeDeviceArrays();
770abed4969SSiddharth Bhat 
771fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
772fa7b0802STobias Grosser   IslNodeBuilder::finalize();
773fa7b0802STobias Grosser }
774fa7b0802STobias Grosser 
775fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
776c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
777c4a4af47SSiddharth Bhat          "Managed memory will directly send host pointers "
778abed4969SSiddharth Bhat          "to the kernel. There is no need for device arrays");
7798ea1fc19STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
780fa7b0802STobias Grosser 
781fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
782fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
78313c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7847287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7857287aeddSTobias Grosser     DevArrayName.append(Array->name);
786fa7b0802STobias Grosser 
78713c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
788aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
789aaabbbf8STobias Grosser     if (Offset)
790aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
791aaabbbf8STobias Grosser           ArraySize,
792aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
793aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
79434eeabbcSSiddharth Bhat     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
79534eeabbcSSiddharth Bhat     // It makes no sense to have an array of size 0. The CUDA API will
79634eeabbcSSiddharth Bhat     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
79734eeabbcSSiddharth Bhat     // choose to be defensive and catch this at the compile phase. It is
79834eeabbcSSiddharth Bhat     // most likely that we are doing something wrong with size computation.
79934eeabbcSSiddharth Bhat     if (SizeSCEV->isZero()) {
80034eeabbcSSiddharth Bhat       errs() << getUniqueScopName(&S)
80134eeabbcSSiddharth Bhat              << " has computed array size 0: " << *ArraySize
80234eeabbcSSiddharth Bhat              << " | for array: " << *(ScopArray->getBasePtr())
80334eeabbcSSiddharth Bhat              << ". This is illegal, exiting.\n";
80434eeabbcSSiddharth Bhat       report_fatal_error("array size was computed to be 0");
80534eeabbcSSiddharth Bhat     }
80634eeabbcSSiddharth Bhat 
8077287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
8087287aeddSTobias Grosser     DevArray->setName(DevArrayName);
80913c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
810fa7b0802STobias Grosser   }
811fa7b0802STobias Grosser 
812fa7b0802STobias Grosser   isl_ast_build_free(Build);
813fa7b0802STobias Grosser }
814fa7b0802STobias Grosser 
815b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() {
816c4a4af47SSiddharth Bhat   assert(PollyManagedMemory &&
817b99c1171STobias Grosser          "Device array most only be prepared in managed-memory mode");
818b99c1171STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
819b99c1171STobias Grosser     gpu_array_info *Array = &Prog->array[i];
820b99c1171STobias Grosser     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
821b99c1171STobias Grosser     Value *HostPtr;
822b99c1171STobias Grosser 
823b99c1171STobias Grosser     if (gpu_array_is_scalar(Array))
824b99c1171STobias Grosser       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
825b99c1171STobias Grosser     else
826b99c1171STobias Grosser       HostPtr = ScopArray->getBasePtr();
827b99c1171STobias Grosser     HostPtr = getLatestValue(HostPtr);
828b99c1171STobias Grosser 
829b99c1171STobias Grosser     Value *Offset = getArrayOffset(Array);
830b99c1171STobias Grosser     if (Offset) {
831b99c1171STobias Grosser       HostPtr = Builder.CreatePointerCast(
832b99c1171STobias Grosser           HostPtr, ScopArray->getElementType()->getPointerTo());
833b99c1171STobias Grosser       HostPtr = Builder.CreateGEP(HostPtr, Offset);
834b99c1171STobias Grosser     }
835b99c1171STobias Grosser 
836b99c1171STobias Grosser     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
837b99c1171STobias Grosser     DeviceAllocations[ScopArray] = HostPtr;
838b99c1171STobias Grosser   }
839b99c1171STobias Grosser }
840b99c1171STobias Grosser 
841c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
842c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
843c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
844c1c6a2a6STobias Grosser 
845c1c6a2a6STobias Grosser   for (auto &F : *M) {
846c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
847c1c6a2a6STobias Grosser       continue;
848c1c6a2a6STobias Grosser 
849c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
850c1c6a2a6STobias Grosser 
851c1c6a2a6STobias Grosser     Metadata *Elements[] = {
852c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
853c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
854c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
855c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
856c1c6a2a6STobias Grosser     };
857c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
858c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
859c1c6a2a6STobias Grosser   }
860c1c6a2a6STobias Grosser }
861c1c6a2a6STobias Grosser 
8627287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
863c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
86413c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
86513c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
8667287aeddSTobias Grosser }
8677287aeddSTobias Grosser 
86857793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
86957793596STobias Grosser   const char *Name = "polly_getKernel";
87057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
87157793596STobias Grosser   Function *F = M->getFunction(Name);
87257793596STobias Grosser 
87357793596STobias Grosser   // If F is not available, declare it.
87457793596STobias Grosser   if (!F) {
87557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
87657793596STobias Grosser     std::vector<Type *> Args;
87757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87857793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
87957793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
88057793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
88157793596STobias Grosser   }
88257793596STobias Grosser 
88357793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
88457793596STobias Grosser }
88557793596STobias Grosser 
88679a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
88779a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
88879a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
88979a947c2STobias Grosser   Function *F = M->getFunction(Name);
89079a947c2STobias Grosser 
89179a947c2STobias Grosser   // If F is not available, declare it.
89279a947c2STobias Grosser   if (!F) {
89379a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
89479a947c2STobias Grosser     std::vector<Type *> Args;
89579a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89679a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
89779a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
89879a947c2STobias Grosser   }
89979a947c2STobias Grosser 
90079a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
90179a947c2STobias Grosser }
90279a947c2STobias Grosser 
90379a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
90479a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
90579a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
90679a947c2STobias Grosser                                             Value *Parameters) {
90779a947c2STobias Grosser   const char *Name = "polly_launchKernel";
90879a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90979a947c2STobias Grosser   Function *F = M->getFunction(Name);
91079a947c2STobias Grosser 
91179a947c2STobias Grosser   // If F is not available, declare it.
91279a947c2STobias Grosser   if (!F) {
91379a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
91479a947c2STobias Grosser     std::vector<Type *> Args;
91579a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
91979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
92079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
92179a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
92279a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
92379a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
92479a947c2STobias Grosser   }
92579a947c2STobias Grosser 
926ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
92779a947c2STobias Grosser                          BlockDimZ, Parameters});
92879a947c2STobias Grosser }
92979a947c2STobias Grosser 
93057793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
93157793596STobias Grosser   const char *Name = "polly_freeKernel";
93257793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
93357793596STobias Grosser   Function *F = M->getFunction(Name);
93457793596STobias Grosser 
93557793596STobias Grosser   // If F is not available, declare it.
93657793596STobias Grosser   if (!F) {
93757793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93857793596STobias Grosser     std::vector<Type *> Args;
93957793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
94057793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
94157793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
94257793596STobias Grosser   }
94357793596STobias Grosser 
94457793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
94557793596STobias Grosser }
94657793596STobias Grosser 
9477287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
948c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
949c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
950abed4969SSiddharth Bhat          "for device");
9517287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
9527287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9537287aeddSTobias Grosser   Function *F = M->getFunction(Name);
9547287aeddSTobias Grosser 
9557287aeddSTobias Grosser   // If F is not available, declare it.
9567287aeddSTobias Grosser   if (!F) {
9577287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
9587287aeddSTobias Grosser     std::vector<Type *> Args;
9597287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
9607287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
9617287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
9627287aeddSTobias Grosser   }
9637287aeddSTobias Grosser 
9647287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
9657287aeddSTobias Grosser }
9667287aeddSTobias Grosser 
967fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
968c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
969c4a4af47SSiddharth Bhat          "Managed memory does not allocate or free memory "
970abed4969SSiddharth Bhat          "for device");
971fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
972fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
973fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
974fa7b0802STobias Grosser 
975fa7b0802STobias Grosser   // If F is not available, declare it.
976fa7b0802STobias Grosser   if (!F) {
977fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
978fa7b0802STobias Grosser     std::vector<Type *> Args;
979fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
980fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
981fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
982fa7b0802STobias Grosser   }
983fa7b0802STobias Grosser 
984fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
985fa7b0802STobias Grosser }
986fa7b0802STobias Grosser 
98713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
98813c78e4dSTobias Grosser                                                     Value *DeviceData,
98913c78e4dSTobias Grosser                                                     Value *Size) {
990c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
991c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
992abed4969SSiddharth Bhat          "device and host");
99313c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
99413c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
99513c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
99613c78e4dSTobias Grosser 
99713c78e4dSTobias Grosser   // If F is not available, declare it.
99813c78e4dSTobias Grosser   if (!F) {
99913c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
100013c78e4dSTobias Grosser     std::vector<Type *> Args;
100113c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
100213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
100313c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
100413c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
100513c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
100613c78e4dSTobias Grosser   }
100713c78e4dSTobias Grosser 
100813c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
100913c78e4dSTobias Grosser }
101013c78e4dSTobias Grosser 
101113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
101213c78e4dSTobias Grosser                                                     Value *HostData,
101313c78e4dSTobias Grosser                                                     Value *Size) {
1014c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory &&
1015c4a4af47SSiddharth Bhat          "Managed memory does not transfer memory between "
1016abed4969SSiddharth Bhat          "device and host");
101713c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
101813c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
101913c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
102013c78e4dSTobias Grosser 
102113c78e4dSTobias Grosser   // If F is not available, declare it.
102213c78e4dSTobias Grosser   if (!F) {
102313c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
102413c78e4dSTobias Grosser     std::vector<Type *> Args;
102513c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
102613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
102713c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
102813c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
102913c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
103013c78e4dSTobias Grosser   }
103113c78e4dSTobias Grosser 
103213c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
103313c78e4dSTobias Grosser }
103413c78e4dSTobias Grosser 
1035abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
1036c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1037abed4969SSiddharth Bhat                                "managed memory");
1038abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
1039abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1040abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
1041abed4969SSiddharth Bhat 
1042abed4969SSiddharth Bhat   // If F is not available, declare it.
1043abed4969SSiddharth Bhat   if (!F) {
1044abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1045abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1046abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
1047abed4969SSiddharth Bhat   }
1048abed4969SSiddharth Bhat 
1049abed4969SSiddharth Bhat   Builder.CreateCall(F);
1050abed4969SSiddharth Bhat }
1051abed4969SSiddharth Bhat 
1052fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
105317f01968SSiddharth Bhat   const char *Name;
105417f01968SSiddharth Bhat 
105517f01968SSiddharth Bhat   switch (Runtime) {
105617f01968SSiddharth Bhat   case GPURuntime::CUDA:
105717f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
105817f01968SSiddharth Bhat     break;
105917f01968SSiddharth Bhat   case GPURuntime::OpenCL:
106017f01968SSiddharth Bhat     Name = "polly_initContextCL";
106117f01968SSiddharth Bhat     break;
106217f01968SSiddharth Bhat   }
106317f01968SSiddharth Bhat 
1064fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1065fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1066fa7b0802STobias Grosser 
1067fa7b0802STobias Grosser   // If F is not available, declare it.
1068fa7b0802STobias Grosser   if (!F) {
1069fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1070fa7b0802STobias Grosser     std::vector<Type *> Args;
1071fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1072fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1073fa7b0802STobias Grosser   }
1074fa7b0802STobias Grosser 
1075fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
1076fa7b0802STobias Grosser }
1077fa7b0802STobias Grosser 
1078fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1079fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
1080fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1081fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
1082fa7b0802STobias Grosser 
1083fa7b0802STobias Grosser   // If F is not available, declare it.
1084fa7b0802STobias Grosser   if (!F) {
1085fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1086fa7b0802STobias Grosser     std::vector<Type *> Args;
1087fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1088fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1089fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1090fa7b0802STobias Grosser   }
1091fa7b0802STobias Grosser 
1092fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1093fa7b0802STobias Grosser }
1094fa7b0802STobias Grosser 
10955260c041STobias Grosser /// Check if one string is a prefix of another.
10965260c041STobias Grosser ///
10975260c041STobias Grosser /// @param String The string in which to look for the prefix.
10985260c041STobias Grosser /// @param Prefix The prefix to look for.
10995260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
11005260c041STobias Grosser   return String.find(Prefix) == 0;
11015260c041STobias Grosser }
11025260c041STobias Grosser 
110313c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1104b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
110513c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
110613c78e4dSTobias Grosser 
110713c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1108718d04c6STobias Grosser     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1109f7face4bSSiddharth Bhat 
1110f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1111f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
111213c78e4dSTobias Grosser 
111313c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1114f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1115f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1116f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
111713c78e4dSTobias Grosser     }
111813c78e4dSTobias Grosser 
1119f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1120b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1121b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
112213c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
112313c78e4dSTobias Grosser   }
112413c78e4dSTobias Grosser   return ArraySize;
112513c78e4dSTobias Grosser }
112613c78e4dSTobias Grosser 
1127aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1128aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1129aaabbbf8STobias Grosser     return nullptr;
1130aaabbbf8STobias Grosser 
1131b65ccc43STobias Grosser   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1132aaabbbf8STobias Grosser 
1133718d04c6STobias Grosser   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1134aaabbbf8STobias Grosser 
1135ccbf4b50SSiddharth Bhat   isl::set ZeroSet = isl::set::universe(Min.get_space());
1136aaabbbf8STobias Grosser 
11373044dc51SMichael Kruse   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++)
1138ccbf4b50SSiddharth Bhat     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1139aaabbbf8STobias Grosser 
1140ccbf4b50SSiddharth Bhat   if (Min.is_subset(ZeroSet)) {
1141aaabbbf8STobias Grosser     return nullptr;
1142aaabbbf8STobias Grosser   }
1143aaabbbf8STobias Grosser 
1144ccbf4b50SSiddharth Bhat   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1145aaabbbf8STobias Grosser 
11463044dc51SMichael Kruse   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++) {
1147aaabbbf8STobias Grosser     if (i > 0) {
1148ccbf4b50SSiddharth Bhat       isl::pw_aff Bound_I =
1149ccbf4b50SSiddharth Bhat           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1150ccbf4b50SSiddharth Bhat       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1151ccbf4b50SSiddharth Bhat       Result = Result.mul(BExpr);
1152aaabbbf8STobias Grosser     }
1153ccbf4b50SSiddharth Bhat     isl::pw_aff DimMin = Min.dim_min(i);
1154ccbf4b50SSiddharth Bhat     isl::ast_expr MExpr = Build.expr_from(DimMin);
1155ccbf4b50SSiddharth Bhat     Result = Result.add(MExpr);
1156aaabbbf8STobias Grosser   }
1157aaabbbf8STobias Grosser 
1158ccbf4b50SSiddharth Bhat   return ExprBuilder.create(Result.release());
1159aaabbbf8STobias Grosser }
1160aaabbbf8STobias Grosser 
1161b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1162abed4969SSiddharth Bhat                                              ScopArrayInfo *ArrayInfo) {
1163c4a4af47SSiddharth Bhat   assert(PollyManagedMemory && "Only used when you wish to get a host "
1164abed4969SSiddharth Bhat                                "pointer for sending data to the kernel, "
1165abed4969SSiddharth Bhat                                "with managed memory");
1166abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1167b99c1171STobias Grosser   it = DeviceAllocations.find(ArrayInfo);
1168b99c1171STobias Grosser   assert(it != DeviceAllocations.end() &&
1169b99c1171STobias Grosser          "Device array expected to be available");
1170abed4969SSiddharth Bhat   return it->second;
1171abed4969SSiddharth Bhat }
1172abed4969SSiddharth Bhat 
117313c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
117413c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1175c4a4af47SSiddharth Bhat   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
117613c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
117713c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
117813c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
117913c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
118013c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
118113c78e4dSTobias Grosser 
118213c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1183aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
118413c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
118513c78e4dSTobias Grosser 
1186b06ff457STobias Grosser   Value *HostPtr;
1187b06ff457STobias Grosser 
1188b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1189b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1190b06ff457STobias Grosser   else
1191b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
1192edf9581eSSiddharth Bhat   HostPtr = getLatestValue(HostPtr);
119313c78e4dSTobias Grosser 
1194aaabbbf8STobias Grosser   if (Offset) {
1195aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1196aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1197aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1198aaabbbf8STobias Grosser   }
1199aaabbbf8STobias Grosser 
120013c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
120113c78e4dSTobias Grosser 
1202aaabbbf8STobias Grosser   if (Offset) {
1203aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1204ff40087aSTobias Grosser         Size, Builder.CreateMul(
1205ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1206aaabbbf8STobias Grosser   }
1207aaabbbf8STobias Grosser 
120813c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
120913c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
121013c78e4dSTobias Grosser   else
121113c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
121213c78e4dSTobias Grosser 
121313c78e4dSTobias Grosser   isl_id_free(Id);
121413c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
121513c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
121613c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
121713c78e4dSTobias Grosser }
121813c78e4dSTobias Grosser 
12191fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
122032837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
122132837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
122232837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
122332837fe3STobias Grosser   isl_id_free(Id);
122432837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
122532837fe3STobias Grosser 
122632837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
122732837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
122832837fe3STobias Grosser     createKernel(UserStmt);
122962acb344STobias Grosser     if (PollyManagedMemory)
123062acb344STobias Grosser       createCallSynchronizeDevice();
123132837fe3STobias Grosser     isl_ast_expr_free(Expr);
123232837fe3STobias Grosser     return;
123332837fe3STobias Grosser   }
12349e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
12359e3db2b7SSiddharth Bhat     initializeAfterRTH();
12369e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12379e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12389e3db2b7SSiddharth Bhat     return;
12399e3db2b7SSiddharth Bhat   }
12409e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
12419e3db2b7SSiddharth Bhat     finalize();
12429e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
12439e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
12449e3db2b7SSiddharth Bhat     return;
12459e3db2b7SSiddharth Bhat   }
124613c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1247c4a4af47SSiddharth Bhat     if (!PollyManagedMemory)
124813c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1249abed4969SSiddharth Bhat     else
1250abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1251abed4969SSiddharth Bhat 
125232837fe3STobias Grosser     isl_ast_expr_free(Expr);
125313c78e4dSTobias Grosser     return;
125413c78e4dSTobias Grosser   }
125513c78e4dSTobias Grosser 
125613c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1257c4a4af47SSiddharth Bhat     if (!PollyManagedMemory) {
125813c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1259abed4969SSiddharth Bhat     } else {
1260abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1261abed4969SSiddharth Bhat     }
126213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
126338fc0aedSTobias Grosser     return;
126438fc0aedSTobias Grosser   }
126538fc0aedSTobias Grosser 
12665260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12675260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12685260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12695260c041STobias Grosser   isl_id_free(Anno);
12705260c041STobias Grosser 
12715260c041STobias Grosser   switch (KernelStmt->type) {
12725260c041STobias Grosser   case ppcg_kernel_domain:
1273edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12745260c041STobias Grosser     isl_ast_node_free(UserStmt);
12755260c041STobias Grosser     return;
12765260c041STobias Grosser   case ppcg_kernel_copy:
1277b513b491STobias Grosser     createKernelCopy(KernelStmt);
12785260c041STobias Grosser     isl_ast_expr_free(Expr);
12795260c041STobias Grosser     isl_ast_node_free(UserStmt);
12805260c041STobias Grosser     return;
12815260c041STobias Grosser   case ppcg_kernel_sync:
12825260c041STobias Grosser     createKernelSync();
12835260c041STobias Grosser     isl_ast_expr_free(Expr);
12845260c041STobias Grosser     isl_ast_node_free(UserStmt);
12855260c041STobias Grosser     return;
12865260c041STobias Grosser   }
12875260c041STobias Grosser 
12885260c041STobias Grosser   isl_ast_expr_free(Expr);
12895260c041STobias Grosser   isl_ast_node_free(UserStmt);
12905260c041STobias Grosser }
129153c80387SPhilip Pfaffe 
129253c80387SPhilip Pfaffe void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
129342ad8182SMichael Kruse   createForSequential(isl::manage(Node), false);
129453c80387SPhilip Pfaffe }
129553c80387SPhilip Pfaffe 
1296b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1297b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1298b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1299b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1300b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1301b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1302b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1303b513b491STobias Grosser 
1304b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1305b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1306b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1307b513b491STobias Grosser   } else {
1308b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1309b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1310b513b491STobias Grosser   }
1311b513b491STobias Grosser }
13125260c041STobias Grosser 
1313edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1314edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1315edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1316edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1317edb885cbSTobias Grosser 
1318edb885cbSTobias Grosser   LoopToScevMapT LTS;
1319edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1320edb885cbSTobias Grosser 
1321edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1322edb885cbSTobias Grosser 
1323edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1324edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1325edb885cbSTobias Grosser   else
1326a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1327edb885cbSTobias Grosser }
1328edb885cbSTobias Grosser 
13295260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
13305260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13312f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
133217f01968SSiddharth Bhat 
133317f01968SSiddharth Bhat   Function *Sync;
133417f01968SSiddharth Bhat 
133517f01968SSiddharth Bhat   switch (Arch) {
13362f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
13372f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
13382f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
13392f3073b5SPhilipp Schaad 
13402f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
13412f3073b5SPhilipp Schaad     if (!Sync) {
13422f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
13432f3073b5SPhilipp Schaad       std::vector<Type *> Args;
13442f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
13452f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
13462f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
13472f3073b5SPhilipp Schaad     }
13482f3073b5SPhilipp Schaad     break;
134917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
135017f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
135117f01968SSiddharth Bhat     break;
135217f01968SSiddharth Bhat   }
135317f01968SSiddharth Bhat 
13545260c041STobias Grosser   Builder.CreateCall(Sync, {});
13555260c041STobias Grosser }
13565260c041STobias Grosser 
1357edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1358edb885cbSTobias Grosser ///
1359edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1360edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1361edb885cbSTobias Grosser ///
1362edb885cbSTobias Grosser /// @param Node The node to collect references for.
1363edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1364edb885cbSTobias Grosser ///
1365edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1366edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1367edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1368edb885cbSTobias Grosser     return isl_bool_true;
1369edb885cbSTobias Grosser 
1370edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1371edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1372edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1373edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1374edb885cbSTobias Grosser   isl_id_free(Id);
1375edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1376edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1377edb885cbSTobias Grosser 
1378edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1379edb885cbSTobias Grosser     return isl_bool_true;
1380edb885cbSTobias Grosser 
1381edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1382edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1383edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1384edb885cbSTobias Grosser   isl_id_free(Id);
1385edb885cbSTobias Grosser 
138600bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1387edb885cbSTobias Grosser 
1388edb885cbSTobias Grosser   return isl_bool_true;
1389edb885cbSTobias Grosser }
1390edb885cbSTobias Grosser 
13918fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice.
13928fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = {
139356572c6aSSiddharth Bhat     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
139456572c6aSSiddharth Bhat     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
139556572c6aSSiddharth Bhat 
139656572c6aSSiddharth Bhat // A map from intrinsics to their corresponding libdevice functions.
139756572c6aSSiddharth Bhat const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
139856572c6aSSiddharth Bhat     {"llvm.exp.f64", "exp"},
139956572c6aSSiddharth Bhat     {"llvm.exp.f32", "expf"},
140056572c6aSSiddharth Bhat     {"llvm.powi.f64", "powi"},
140156572c6aSSiddharth Bhat     {"llvm.powi.f32", "powif"}};
14028fc6cdfbSTobias Grosser 
140366a05ad6SPhilip Pfaffe /// Return the corresponding CUDA libdevice function name @p Name.
140456572c6aSSiddharth Bhat /// Note that this function will try to convert instrinsics in the list
140556572c6aSSiddharth Bhat /// IntrinsicToLibdeviceFunc into libdevice functions.
140656572c6aSSiddharth Bhat /// This is because some intrinsics such as `exp`
140756572c6aSSiddharth Bhat /// are not supported by the NVPTX backend.
140856572c6aSSiddharth Bhat /// If this restriction of the backend is lifted, we should refactor our code
140956572c6aSSiddharth Bhat /// so that we use intrinsics whenever possible.
14108fc6cdfbSTobias Grosser ///
14118fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA.
141266a05ad6SPhilip Pfaffe std::string getCUDALibDeviceFuntion(StringRef Name) {
141366a05ad6SPhilip Pfaffe   auto It = IntrinsicToLibdeviceFunc.find(Name);
141456572c6aSSiddharth Bhat   if (It != IntrinsicToLibdeviceFunc.end())
141566a05ad6SPhilip Pfaffe     return getCUDALibDeviceFuntion(It->second);
141656572c6aSSiddharth Bhat 
141766a05ad6SPhilip Pfaffe   if (CUDALibDeviceFunctions.count(Name))
141866a05ad6SPhilip Pfaffe     return ("__nv_" + Name).str();
14198fc6cdfbSTobias Grosser 
14208fc6cdfbSTobias Grosser   return "";
14218fc6cdfbSTobias Grosser }
14228fc6cdfbSTobias Grosser 
1423f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
14248fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1425f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1426f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
142754491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
142854491db6STobias Grosser   // "llvm.copysign".
142954491db6STobias Grosser   const StringRef Name = F->getName();
14308fc6cdfbSTobias Grosser 
143166a05ad6SPhilip Pfaffe   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
14328fc6cdfbSTobias Grosser     return true;
14338fc6cdfbSTobias Grosser 
143454491db6STobias Grosser   return F->isIntrinsic() &&
143554491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
143656572c6aSSiddharth Bhat           Name.startswith("llvm.copysign"));
1437f291c8d5SSiddharth Bhat }
1438f291c8d5SSiddharth Bhat 
1439f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1440f291c8d5SSiddharth Bhat ///
1441f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1442f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1443f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1444f291c8d5SSiddharth Bhat /// `Function`s.
1445f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1446f291c8d5SSiddharth Bhat 
1447f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1448f291c8d5SSiddharth Bhat static SetVector<Function *>
14498fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
14508fc6cdfbSTobias Grosser                                  bool AllowCUDALibDevice) {
1451f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1452f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1453f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1454f291c8d5SSiddharth Bhat     if (F) {
14558fc6cdfbSTobias Grosser       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
14568fc6cdfbSTobias Grosser              "Code should have bailed out by "
1457f291c8d5SSiddharth Bhat              "this point if an invalid function "
1458f291c8d5SSiddharth Bhat              "were present in a kernel.");
1459f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1460f291c8d5SSiddharth Bhat     }
1461f291c8d5SSiddharth Bhat   }
1462f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1463f291c8d5SSiddharth Bhat }
1464f291c8d5SSiddharth Bhat 
146543df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
146643df2020STobias Grosser            isl::space>
1467f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1468edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1469edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1470edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
147143df2020STobias Grosser   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1472edb885cbSTobias Grosser   SubtreeReferences References = {
147343df2020STobias Grosser       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
147443df2020STobias Grosser       &ParamSpace};
1475edb885cbSTobias Grosser 
1476edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1477edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1478edb885cbSTobias Grosser 
1479e53c924bSSiddharth Bhat   // NOTE: this is populated in IslNodeBuilder::addParameters
1480e53c924bSSiddharth Bhat   // See [Code generation of induction variables of loops outside Scops].
1481e53c924bSSiddharth Bhat   for (const auto &I : OutsideLoopIterations)
1482e53c924bSSiddharth Bhat     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1483e53c924bSSiddharth Bhat 
1484edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1485edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1486edb885cbSTobias Grosser 
1487e53c924bSSiddharth Bhat   for (const SCEV *Expr : SCEVs) {
1488edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1489e53c924bSSiddharth Bhat     findLoops(Expr, Loops);
1490e53c924bSSiddharth Bhat   }
1491e53c924bSSiddharth Bhat 
1492e53c924bSSiddharth Bhat   Loops.remove_if([this](const Loop *L) {
1493e53c924bSSiddharth Bhat     return S.contains(L) || L->contains(S.getEntry());
1494e53c924bSSiddharth Bhat   });
1495edb885cbSTobias Grosser 
1496edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1497d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1498edb885cbSTobias Grosser 
1499b65ccc43STobias Grosser   isl_space *Space = S.getParamSpace().release();
15003044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1501edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1502edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1503edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1504edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1505edb885cbSTobias Grosser     isl_id_free(Id);
1506edb885cbSTobias Grosser   }
1507edb885cbSTobias Grosser   isl_space_free(Space);
1508edb885cbSTobias Grosser 
15093044dc51SMichael Kruse   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1510edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1511edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1512edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1513edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1514edb885cbSTobias Grosser     isl_id_free(Id);
1515edb885cbSTobias Grosser   }
1516edb885cbSTobias Grosser 
1517f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1518f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1519f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1520f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1521f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1522f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1523f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1524f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1525f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
15268fc6cdfbSTobias Grosser 
15278fc6cdfbSTobias Grosser   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
15288fc6cdfbSTobias Grosser 
1529f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
15308fc6cdfbSTobias Grosser       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1531f291c8d5SSiddharth Bhat 
1532a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1533a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1534a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1535a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1536a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1537a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1538a1b2086aSSiddharth Bhat     else
1539a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1540a1b2086aSSiddharth Bhat   }
154143df2020STobias Grosser   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
154243df2020STobias Grosser                          ParamSpace);
1543edb885cbSTobias Grosser }
1544edb885cbSTobias Grosser 
154574dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
154674dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
154774dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
154874dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
154974dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
155074dc3cb4STobias Grosser 
155174dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
155274dc3cb4STobias Grosser     DT.eraseNode(BB);
155374dc3cb4STobias Grosser }
155474dc3cb4STobias Grosser 
155574dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
15564d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15574d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
155874dc3cb4STobias Grosser     if (L)
155974dc3cb4STobias Grosser       SE.forgetLoop(L);
156074dc3cb4STobias Grosser   }
15614d50ab86SPhilip Pfaffe }
156274dc3cb4STobias Grosser 
156374dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
1564c06a6380SPhilip Pfaffe   SmallSet<Loop *, 1> WorkList;
15654d50ab86SPhilip Pfaffe   for (BasicBlock &BB : *F) {
15664d50ab86SPhilip Pfaffe     Loop *L = LI.getLoopFor(&BB);
15674d50ab86SPhilip Pfaffe     if (L)
1568c06a6380SPhilip Pfaffe       WorkList.insert(L);
15694d50ab86SPhilip Pfaffe   }
1570c06a6380SPhilip Pfaffe   for (auto *L : WorkList)
1571c06a6380SPhilip Pfaffe     LI.erase(L);
157274dc3cb4STobias Grosser }
157374dc3cb4STobias Grosser 
157479a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
157579a947c2STobias Grosser   std::vector<Value *> Sizes;
15768ea1fc19STobias Grosser   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
157779a947c2STobias Grosser 
1578718d04c6STobias Grosser   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
157979a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
15804d5820d1SSiddharth Bhat     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
15814d5820d1SSiddharth Bhat     isl::ast_expr GridSize = Context.expr_from(Size);
15824d5820d1SSiddharth Bhat     Value *Res = ExprBuilder.create(GridSize.release());
158379a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
158479a947c2STobias Grosser     Sizes.push_back(Res);
158579a947c2STobias Grosser   }
158679a947c2STobias Grosser 
158779a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
158879a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
158979a947c2STobias Grosser 
159079a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
159179a947c2STobias Grosser }
159279a947c2STobias Grosser 
159379a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
159479a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
159579a947c2STobias Grosser   std::vector<Value *> Sizes;
159679a947c2STobias Grosser 
159779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
159879a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
159979a947c2STobias Grosser     Sizes.push_back(Res);
160079a947c2STobias Grosser   }
160179a947c2STobias Grosser 
160279a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
160379a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
160479a947c2STobias Grosser 
160579a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
160679a947c2STobias Grosser }
160779a947c2STobias Grosser 
1608a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1609a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1610a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1611a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1612a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1613a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1614a90be207SSiddharth Bhat }
1615a90be207SSiddharth Bhat 
161657693272STobias Grosser Value *
161757693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
161857693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1619a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1620a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1621a90be207SSiddharth Bhat 
162250139f0fSPhilipp Schaad   // If we are using the OpenCL Runtime, we need to add the kernel argument
162350139f0fSPhilipp Schaad   // sizes to the end of the launch-parameter list, so OpenCL can determine
162450139f0fSPhilipp Schaad   // how big the respective kernel arguments are.
162550139f0fSPhilipp Schaad   // Here we need to reserve adequate space for that.
162650139f0fSPhilipp Schaad   Type *ArrayTy;
162750139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL)
162850139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
162950139f0fSPhilipp Schaad   else
163050139f0fSPhilipp Schaad     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
163179a947c2STobias Grosser 
163279a947c2STobias Grosser   BasicBlock *EntryBlock =
163379a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
163467726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
163579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
163667726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
163767726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
163879a947c2STobias Grosser 
163979a947c2STobias Grosser   int Index = 0;
164079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
164179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
164279a947c2STobias Grosser       continue;
164379a947c2STobias Grosser 
164479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1645206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
164679a947c2STobias Grosser 
164750139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1648a90be207SSiddharth Bhat       ArgSizes[Index] = SAI->getElemSizeInBytes();
1649a90be207SSiddharth Bhat 
1650abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1651c4a4af47SSiddharth Bhat     if (PollyManagedMemory) {
1652b99c1171STobias Grosser       DevArray = getManagedDeviceArray(&Prog->array[i],
1653b99c1171STobias Grosser                                        const_cast<ScopArrayInfo *>(SAI));
1654abed4969SSiddharth Bhat     } else {
1655abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
165679a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1657abed4969SSiddharth Bhat     }
1658abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1659abed4969SSiddharth Bhat                                   "initialized");
1660aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1661aaabbbf8STobias Grosser 
1662aaabbbf8STobias Grosser     if (Offset) {
1663aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1664aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1665aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1666aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1667aaabbbf8STobias Grosser     }
1668fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1669fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1670aaabbbf8STobias Grosser 
1671fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1672abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1673c4a4af47SSiddharth Bhat       if (PollyManagedMemory)
1674abed4969SSiddharth Bhat         ValPtr = DevArray;
1675abed4969SSiddharth Bhat       else
1676abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1677abed4969SSiddharth Bhat 
1678abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1679abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1680fe74a7a1STobias Grosser       Value *ValPtrCast =
1681fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1682fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1683fe74a7a1STobias Grosser     } else {
168467726b32STobias Grosser       Instruction *Param =
168567726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
168667726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
168779a947c2STobias Grosser                          EntryBlock->getTerminator());
168879a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
168979a947c2STobias Grosser       Value *ParamTyped =
169079a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
169179a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1692fe74a7a1STobias Grosser     }
169379a947c2STobias Grosser     Index++;
169479a947c2STobias Grosser   }
169579a947c2STobias Grosser 
1696a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1697a490147cSTobias Grosser 
1698a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1699a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1700a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1701a490147cSTobias Grosser     isl_id_free(Id);
1702a90be207SSiddharth Bhat 
170350139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1704a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1705a90be207SSiddharth Bhat 
170667726b32STobias Grosser     Instruction *Param =
170767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
170867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1709a490147cSTobias Grosser                        EntryBlock->getTerminator());
1710a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1711a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1712a490147cSTobias Grosser     Index++;
1713a490147cSTobias Grosser   }
1714a490147cSTobias Grosser 
1715d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1716d8b94bcaSTobias Grosser 
1717d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1718d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1719d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1720a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1721a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1722d8b94bcaSTobias Grosser     isl_id_free(Id);
1723a90be207SSiddharth Bhat 
172450139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1725a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1726a90be207SSiddharth Bhat 
172767726b32STobias Grosser     Instruction *Param =
172867726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
172967726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1730d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1731d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1732a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1733d8b94bcaSTobias Grosser     Index++;
1734d8b94bcaSTobias Grosser   }
1735d8b94bcaSTobias Grosser 
173657693272STobias Grosser   for (auto Val : SubtreeValues) {
173750139f0fSPhilipp Schaad     if (Runtime == GPURuntime::OpenCL)
1738a90be207SSiddharth Bhat       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1739a90be207SSiddharth Bhat 
174067726b32STobias Grosser     Instruction *Param =
174167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
174267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
174357693272STobias Grosser                        EntryBlock->getTerminator());
174457693272STobias Grosser     Builder.CreateStore(Val, Param);
1745a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1746a90be207SSiddharth Bhat     Index++;
1747a90be207SSiddharth Bhat   }
1748a90be207SSiddharth Bhat 
174950139f0fSPhilipp Schaad   if (Runtime == GPURuntime::OpenCL) {
1750a90be207SSiddharth Bhat     for (int i = 0; i < NumArgs; i++) {
1751a90be207SSiddharth Bhat       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1752a90be207SSiddharth Bhat       Instruction *Param =
1753a90be207SSiddharth Bhat           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1754a90be207SSiddharth Bhat                          Launch + "_param_size_" + std::to_string(i),
1755a90be207SSiddharth Bhat                          EntryBlock->getTerminator());
1756a90be207SSiddharth Bhat       Builder.CreateStore(Val, Param);
1757a90be207SSiddharth Bhat       insertStoreParameter(Parameters, Param, Index);
175857693272STobias Grosser       Index++;
175957693272STobias Grosser     }
176050139f0fSPhilipp Schaad   }
176157693272STobias Grosser 
176279a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
176379a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
176479a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
176579a947c2STobias Grosser }
176679a947c2STobias Grosser 
1767f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1768f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1769f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1770f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1771f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1772f291c8d5SSiddharth Bhat     if (!Clone)
1773f291c8d5SSiddharth Bhat       Clone =
1774f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1775f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1776f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1777f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1778f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1779f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1780f291c8d5SSiddharth Bhat   }
1781f291c8d5SSiddharth Bhat }
178232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
178332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
178432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
178532837fe3STobias Grosser   isl_id_free(Id);
178632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
178732837fe3STobias Grosser 
1788bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1789bc653f20STobias Grosser     DeepestParallel =
1790bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1791bc653f20STobias Grosser   else
1792bc653f20STobias Grosser     DeepestSequential =
1793bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1794bc653f20STobias Grosser 
1795c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1796c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1797c1c6a2a6STobias Grosser 
1798f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1799f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1800e53c924bSSiddharth Bhat   SetVector<const Loop *> Loops;
180143df2020STobias Grosser   isl::space ParamSpace;
180243df2020STobias Grosser   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1803e53c924bSSiddharth Bhat       getReferencesInKernel(Kernel);
1804edb885cbSTobias Grosser 
180543df2020STobias Grosser   // Add parameters that appear only in the access function to the kernel
180643df2020STobias Grosser   // space. This is important to make sure that all isl_ids are passed as
180743df2020STobias Grosser   // parameters to the kernel, even though we may not have all parameters
180843df2020STobias Grosser   // in the context to improve compile time.
180943df2020STobias Grosser   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
181043df2020STobias Grosser 
181132837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
181232837fe3STobias Grosser 
181332837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1814472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1815edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1816587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1817b06ff457STobias Grosser   ScalarMap.clear();
1818c52b71dbSTobias Grosser   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1819c52b71dbSTobias Grosser   EscapeMap.clear();
182032837fe3STobias Grosser 
1821edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1822edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1823edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1824edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1825edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1826edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1827edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1828edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1829edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1830edb885cbSTobias Grosser     SubtreeValues.insert(V);
1831edb885cbSTobias Grosser   }
1832edb885cbSTobias Grosser 
1833f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1834f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
183532837fe3STobias Grosser 
183659ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
183759ab0705STobias Grosser 
183851dfc275STobias Grosser   finalizeKernelArguments(Kernel);
183974dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
18402f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1841c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
184274dc3cb4STobias Grosser   clearDominators(F);
184374dc3cb4STobias Grosser   clearScalarEvolution(F);
184474dc3cb4STobias Grosser   clearLoops(F);
184574dc3cb4STobias Grosser 
1846472f9654STobias Grosser   IDToValue = HostIDs;
184732837fe3STobias Grosser 
1848b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1849b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1850c52b71dbSTobias Grosser   EscapeMap = std::move(HostEscapeMap);
1851edb885cbSTobias Grosser   IDToSAI.clear();
185274dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
185374dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
18544d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
185574dc3cb4STobias Grosser   LocalArrays.clear();
1856edb885cbSTobias Grosser 
185751dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
185851dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
185957693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
186079a947c2STobias Grosser 
186179f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
186257793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
186357793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
186457793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
186579a947c2STobias Grosser 
186679a947c2STobias Grosser   Value *GridDimX, *GridDimY;
186779a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
186879a947c2STobias Grosser 
186979a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
187079a947c2STobias Grosser                          BlockDimZ, Parameters);
187157793596STobias Grosser   createCallFreeKernel(GPUKernel);
1872b513b491STobias Grosser 
1873b513b491STobias Grosser   for (auto Id : KernelIds)
1874b513b491STobias Grosser     isl_id_free(Id);
1875b513b491STobias Grosser 
1876b513b491STobias Grosser   KernelIds.clear();
187732837fe3STobias Grosser }
187832837fe3STobias Grosser 
187932837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
188032837fe3STobias Grosser ///
188132837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
188232837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1883d277fedaSSiddharth Bhat   std::string Ret = "";
188432837fe3STobias Grosser 
1885d277fedaSSiddharth Bhat   if (!is64Bit) {
1886d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
188730caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1888d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1889d277fedaSSiddharth Bhat   } else {
1890d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
189130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1892d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1893d277fedaSSiddharth Bhat   }
189432837fe3STobias Grosser 
189532837fe3STobias Grosser   return Ret;
189632837fe3STobias Grosser }
189732837fe3STobias Grosser 
18982f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
18992f3073b5SPhilipp Schaad ///
19002f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
19012f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
19022f3073b5SPhilipp Schaad   std::string Ret = "";
19032f3073b5SPhilipp Schaad 
19042f3073b5SPhilipp Schaad   if (!is64Bit) {
19052f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
190630caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19072f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19082f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19092f3073b5SPhilipp Schaad   } else {
19102f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
191130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
19122f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
19132f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
19142f3073b5SPhilipp Schaad   }
19152f3073b5SPhilipp Schaad 
19162f3073b5SPhilipp Schaad   return Ret;
19172f3073b5SPhilipp Schaad }
19182f3073b5SPhilipp Schaad 
1919edb885cbSTobias Grosser Function *
1920edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1921edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
192232837fe3STobias Grosser   std::vector<Type *> Args;
192379f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
192432837fe3STobias Grosser 
19252f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
19262f3073b5SPhilipp Schaad 
192732837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
192832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
192932837fe3STobias Grosser       continue;
193032837fe3STobias Grosser 
1931fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1932fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1933206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1934fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
19352f3073b5SPhilipp Schaad       MemoryType.push_back(
19362f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1937fe74a7a1STobias Grosser     } else {
1938d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1939d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
19402f3073b5SPhilipp Schaad       MemoryType.push_back(
19412f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
194232837fe3STobias Grosser     }
1943fe74a7a1STobias Grosser   }
194432837fe3STobias Grosser 
1945f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1946f6044bd0STobias Grosser 
19472f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1948f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
19492f3073b5SPhilipp Schaad     MemoryType.push_back(
19502f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19512f3073b5SPhilipp Schaad   }
1952f6044bd0STobias Grosser 
1953c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1954c84a1995STobias Grosser 
1955cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1956cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1957cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1958cf66ef26STobias Grosser     isl_id_free(Id);
1959cf66ef26STobias Grosser     Args.push_back(Val->getType());
19602f3073b5SPhilipp Schaad     MemoryType.push_back(
19612f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1962cf66ef26STobias Grosser   }
1963c84a1995STobias Grosser 
19642f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1965edb885cbSTobias Grosser     Args.push_back(V->getType());
19662f3073b5SPhilipp Schaad     MemoryType.push_back(
19672f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
19682f3073b5SPhilipp Schaad   }
1969edb885cbSTobias Grosser 
197032837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
197132837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
197232837fe3STobias Grosser                               GPUModule.get());
197317f01968SSiddharth Bhat 
19742f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
19752f3073b5SPhilipp Schaad 
19762f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
19772f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
19782f3073b5SPhilipp Schaad   }
19792f3073b5SPhilipp Schaad 
19802f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
19812f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
19822f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
19832f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
19842f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19852f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
19862f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19872f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
19882f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19892f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
19902f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19912f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
19922f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
19932f3073b5SPhilipp Schaad   }
19942f3073b5SPhilipp Schaad 
199517f01968SSiddharth Bhat   switch (Arch) {
199617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
199732837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
199817f01968SSiddharth Bhat     break;
19992f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20002f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20012f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
20022f3073b5SPhilipp Schaad     break;
200317f01968SSiddharth Bhat   }
200432837fe3STobias Grosser 
200532837fe3STobias Grosser   auto Arg = FN->arg_begin();
200632837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
200732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
200832837fe3STobias Grosser       continue;
200932837fe3STobias Grosser 
2010edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
2011edb885cbSTobias Grosser 
2012edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2013718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2014edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
2015edb885cbSTobias Grosser     Value *Val = &*Arg;
2016edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2017edb885cbSTobias Grosser     isl_ast_build *Build =
2018edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
2019f5aff704SRoman Gareev     Sizes.push_back(nullptr);
20203044dc51SMichael Kruse     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2021edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
20229e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2023edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
2024edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
2025edb885cbSTobias Grosser     }
2026edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
20274d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
202874dc3cb4STobias Grosser     LocalArrays.push_back(Val);
2029edb885cbSTobias Grosser 
2030edb885cbSTobias Grosser     isl_ast_build_free(Build);
2031b513b491STobias Grosser     KernelIds.push_back(Id);
2032edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
203332837fe3STobias Grosser     Arg++;
203432837fe3STobias Grosser   }
203532837fe3STobias Grosser 
2036f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
2037f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2038f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
2039f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
2040f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2041f6044bd0STobias Grosser     Arg++;
2042f6044bd0STobias Grosser   }
2043f6044bd0STobias Grosser 
2044c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
2045c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2046c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
204712453403STobias Grosser     Value *Val = IDToValue[Id];
204812453403STobias Grosser     ValueMap[Val] = &*Arg;
2049c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
2050c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2051c84a1995STobias Grosser     Arg++;
2052c84a1995STobias Grosser   }
2053c84a1995STobias Grosser 
2054edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
2055edb885cbSTobias Grosser     Arg->setName(V->getName());
2056edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
2057edb885cbSTobias Grosser     Arg++;
2058edb885cbSTobias Grosser   }
2059edb885cbSTobias Grosser 
206032837fe3STobias Grosser   return FN;
206132837fe3STobias Grosser }
206232837fe3STobias Grosser 
2063472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
206417f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
206517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
2066472f9654STobias Grosser 
206717f01968SSiddharth Bhat   switch (Arch) {
20682f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
20692f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
20702f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
207117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
207217f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
207317f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
207417f01968SSiddharth Bhat 
207517f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
207617f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
207717f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
207817f01968SSiddharth Bhat     break;
207917f01968SSiddharth Bhat   }
2080472f9654STobias Grosser 
2081472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2082472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
2083472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2084472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2085472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2086472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2087472f9654STobias Grosser     IDToValue[Id] = Val;
2088472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2089472f9654STobias Grosser   };
2090472f9654STobias Grosser 
2091472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
2092472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2093472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
2094472f9654STobias Grosser   }
2095472f9654STobias Grosser 
2096472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
2097472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2098472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
2099472f9654STobias Grosser   }
2100472f9654STobias Grosser }
2101472f9654STobias Grosser 
2102d71493cbSPhilip Pfaffe void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2103d71493cbSPhilip Pfaffe                                            bool SizeTypeIs64bit) {
21042f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
21052f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
21062f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
21072f3073b5SPhilipp Schaad 
21082f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
21092f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
21102f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
2111d71493cbSPhilip Pfaffe   IntegerType *SizeT =
2112d71493cbSPhilip Pfaffe       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
21132f3073b5SPhilipp Schaad 
2114d71493cbSPhilip Pfaffe   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2115d71493cbSPhilip Pfaffe                            IntegerType *SizeT) mutable {
21162f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21172f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
21182f3073b5SPhilipp Schaad 
21192f3073b5SPhilipp Schaad     // If FN is not available, declare it.
21202f3073b5SPhilipp Schaad     if (!FN) {
21212f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
21222f3073b5SPhilipp Schaad       std::vector<Type *> Args;
2123d71493cbSPhilip Pfaffe       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
21242f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
21252f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
21262f3073b5SPhilipp Schaad     }
21272f3073b5SPhilipp Schaad 
21282f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
2129d71493cbSPhilip Pfaffe     if (SizeT == Builder.getInt32Ty())
21302f3073b5SPhilipp Schaad       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
21312f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
21322f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
21332f3073b5SPhilipp Schaad   };
21342f3073b5SPhilipp Schaad 
21352f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
2136d71493cbSPhilip Pfaffe     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
21372f3073b5SPhilipp Schaad 
21382f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
2139d71493cbSPhilip Pfaffe     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
21402f3073b5SPhilipp Schaad }
21412f3073b5SPhilipp Schaad 
214200bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
214300bb5a99STobias Grosser   auto Arg = FN->arg_begin();
214400bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
214500bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
214600bb5a99STobias Grosser       continue;
214700bb5a99STobias Grosser 
214800bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2149718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
215000bb5a99STobias Grosser     isl_id_free(Id);
215100bb5a99STobias Grosser 
215200bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
215300bb5a99STobias Grosser       Arg++;
215400bb5a99STobias Grosser       continue;
215500bb5a99STobias Grosser     }
215600bb5a99STobias Grosser 
2157fe74a7a1STobias Grosser     Value *Val = &*Arg;
2158fe74a7a1STobias Grosser 
2159fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
216000bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2161fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2162fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2163fe74a7a1STobias Grosser     }
2164fe74a7a1STobias Grosser 
2165fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
216600bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
216700bb5a99STobias Grosser 
216800bb5a99STobias Grosser     Arg++;
216900bb5a99STobias Grosser   }
217000bb5a99STobias Grosser }
217100bb5a99STobias Grosser 
217251dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
217351dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
217451dfc275STobias Grosser   auto Arg = FN->arg_begin();
217551dfc275STobias Grosser 
217651dfc275STobias Grosser   bool StoredScalar = false;
217751dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
217851dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
217951dfc275STobias Grosser       continue;
218051dfc275STobias Grosser 
218151dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2182718d04c6STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
218351dfc275STobias Grosser     isl_id_free(Id);
218451dfc275STobias Grosser 
218551dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
218651dfc275STobias Grosser       Arg++;
218751dfc275STobias Grosser       continue;
218851dfc275STobias Grosser     }
218951dfc275STobias Grosser 
219051dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
219151dfc275STobias Grosser       Arg++;
219251dfc275STobias Grosser       continue;
219351dfc275STobias Grosser     }
219451dfc275STobias Grosser 
219551dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
219651dfc275STobias Grosser     Value *ArgPtr = &*Arg;
219751dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
219851dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
219951dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
220051dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
220151dfc275STobias Grosser     StoredScalar = true;
220251dfc275STobias Grosser 
220351dfc275STobias Grosser     Arg++;
220451dfc275STobias Grosser   }
220551dfc275STobias Grosser 
2206638316daSSiddharth Bhat   if (StoredScalar) {
220751dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
220851dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
220951dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
221051dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
2211638316daSSiddharth Bhat     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
221251dfc275STobias Grosser       BuildSuccessful = 0;
2213349506a9SNicola Zaghen       LLVM_DEBUG(
2214638316daSSiddharth Bhat           dbgs() << getUniqueScopName(&S)
2215638316daSSiddharth Bhat                  << " has a store to a scalar value that"
2216638316daSSiddharth Bhat                     " would be undefined to run in parallel. Bailing out.\n";);
2217638316daSSiddharth Bhat     }
2218638316daSSiddharth Bhat   }
221951dfc275STobias Grosser }
222051dfc275STobias Grosser 
2221b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2222b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2223b513b491STobias Grosser 
2224b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2225b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2226b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2227206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2228b513b491STobias Grosser 
2229f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2230b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2231b513b491STobias Grosser 
2232f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2233928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2234b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2235f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2236b513b491STobias Grosser       isl_val_free(Val);
2237b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2238928d7573STobias Grosser     }
2239928d7573STobias Grosser 
2240928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2241928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2242928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2243928d7573STobias Grosser       isl_val_free(Val);
2244b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2245b513b491STobias Grosser     }
2246b513b491STobias Grosser 
2247130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2248130ca30fSTobias Grosser     Value *Allocation;
2249130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2250130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2251130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2252130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2253130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2254f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2255f919d8b3STobias Grosser 
2256130ca30fSTobias Grosser       Allocation = GlobalVar;
2257130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2258130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2259130ca30fSTobias Grosser     } else {
2260130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2261130ca30fSTobias Grosser     }
22624d5a9172STobias Grosser     SAI =
22634d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
226400fd43b3SPhilip Pfaffe     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2265130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2266130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2267b513b491STobias Grosser     KernelIds.push_back(Id);
2268b513b491STobias Grosser     IDToSAI[Id] = SAI;
2269b513b491STobias Grosser   }
2270b513b491STobias Grosser }
2271b513b491STobias Grosser 
2272f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2273f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2274f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
227579f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
227632837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
227717f01968SSiddharth Bhat 
227817f01968SSiddharth Bhat   switch (Arch) {
227917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
228017f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
228132837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
228217f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
228317f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
228432837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
228517f01968SSiddharth Bhat     break;
22862f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22872f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
22882f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
22892f3073b5SPhilipp Schaad     break;
22902f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22912f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
22922f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
22932f3073b5SPhilipp Schaad     break;
229417f01968SSiddharth Bhat   }
229532837fe3STobias Grosser 
2296edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
229732837fe3STobias Grosser 
229859ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
229932837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
230032837fe3STobias Grosser 
230159ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
230259ab0705STobias Grosser 
230332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
230432837fe3STobias Grosser   Builder.CreateRetVoid();
230532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2306472f9654STobias Grosser 
2307629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2308629109b6STobias Grosser 
230900bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2310b513b491STobias Grosser   createKernelVariables(Kernel, FN);
23112f3073b5SPhilipp Schaad 
23122f3073b5SPhilipp Schaad   switch (Arch) {
23132f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2314472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
23152f3073b5SPhilipp Schaad     break;
23162f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
2317d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, false);
2318d71493cbSPhilip Pfaffe     break;
23192f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
2320d71493cbSPhilip Pfaffe     insertKernelCallsSPIR(Kernel, true);
23212f3073b5SPhilipp Schaad     break;
23222f3073b5SPhilipp Schaad   }
232332837fe3STobias Grosser }
232432837fe3STobias Grosser 
232574dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
232617f01968SSiddharth Bhat   llvm::Triple GPUTriple;
232717f01968SSiddharth Bhat 
232817f01968SSiddharth Bhat   switch (Arch) {
232917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
233017f01968SSiddharth Bhat     switch (Runtime) {
233117f01968SSiddharth Bhat     case GPURuntime::CUDA:
233217f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
233317f01968SSiddharth Bhat       break;
233417f01968SSiddharth Bhat     case GPURuntime::OpenCL:
233517f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
233617f01968SSiddharth Bhat       break;
233717f01968SSiddharth Bhat     }
233817f01968SSiddharth Bhat     break;
23392f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23402f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23412f3073b5SPhilipp Schaad     std::string SPIRAssembly;
23422f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
23432f3073b5SPhilipp Schaad     IROstream << *GPUModule;
23442f3073b5SPhilipp Schaad     IROstream.flush();
23452f3073b5SPhilipp Schaad     return SPIRAssembly;
234617f01968SSiddharth Bhat   }
234717f01968SSiddharth Bhat 
234874dc3cb4STobias Grosser   std::string ErrMsg;
234974dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
235074dc3cb4STobias Grosser 
235174dc3cb4STobias Grosser   if (!GPUTarget) {
235274dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
235374dc3cb4STobias Grosser     return "";
235474dc3cb4STobias Grosser   }
235574dc3cb4STobias Grosser 
235674dc3cb4STobias Grosser   TargetOptions Options;
235774dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
235817f01968SSiddharth Bhat 
235917f01968SSiddharth Bhat   std::string subtarget;
236017f01968SSiddharth Bhat 
236117f01968SSiddharth Bhat   switch (Arch) {
236217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
236317f01968SSiddharth Bhat     subtarget = CudaVersion;
236417f01968SSiddharth Bhat     break;
23652f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
23662f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
23672f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
236817f01968SSiddharth Bhat   }
236917f01968SSiddharth Bhat 
237017f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
237117f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
237274dc3cb4STobias Grosser 
237374dc3cb4STobias Grosser   SmallString<0> ASMString;
237474dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
237574dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
237674dc3cb4STobias Grosser 
237774dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
237874dc3cb4STobias Grosser 
23799a45114bSPeter Collingbourne   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr,
23809a45114bSPeter Collingbourne                                    TargetMachine::CGFT_AssemblyFile,
23819a45114bSPeter Collingbourne                                    true /* verify */)) {
238274dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
238374dc3cb4STobias Grosser     return "";
238474dc3cb4STobias Grosser   }
238574dc3cb4STobias Grosser 
238674dc3cb4STobias Grosser   PM.run(*GPUModule);
238774dc3cb4STobias Grosser 
238874dc3cb4STobias Grosser   return ASMStream.str();
238974dc3cb4STobias Grosser }
239074dc3cb4STobias Grosser 
23918fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() {
23925b307cdbSTobias Grosser   bool RequiresLibDevice = false;
23938fc6cdfbSTobias Grosser   for (Function &F : GPUModule->functions()) {
23948fc6cdfbSTobias Grosser     if (!F.isDeclaration())
23958fc6cdfbSTobias Grosser       continue;
23968fc6cdfbSTobias Grosser 
239766a05ad6SPhilip Pfaffe     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
23988fc6cdfbSTobias Grosser     if (CUDALibDeviceFunc.length() != 0) {
239956572c6aSSiddharth Bhat       // We need to handle the case where a module looks like this:
240056572c6aSSiddharth Bhat       // @expf(..)
240156572c6aSSiddharth Bhat       // @llvm.exp.f64(..)
240256572c6aSSiddharth Bhat       // Both of these functions would be renamed to `__nv_expf`.
240356572c6aSSiddharth Bhat       //
240456572c6aSSiddharth Bhat       // So, we must first check for the existence of the libdevice function.
240556572c6aSSiddharth Bhat       // If this exists, we replace our current function with it.
240656572c6aSSiddharth Bhat       //
240756572c6aSSiddharth Bhat       // If it does not exist, we rename the current function to the
240856572c6aSSiddharth Bhat       // libdevice functiono name.
240956572c6aSSiddharth Bhat       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
241056572c6aSSiddharth Bhat         F.replaceAllUsesWith(Replacement);
241156572c6aSSiddharth Bhat       else
24128fc6cdfbSTobias Grosser         F.setName(CUDALibDeviceFunc);
24135b307cdbSTobias Grosser       RequiresLibDevice = true;
24148fc6cdfbSTobias Grosser     }
24158fc6cdfbSTobias Grosser   }
24168fc6cdfbSTobias Grosser 
24175b307cdbSTobias Grosser   return RequiresLibDevice;
24188fc6cdfbSTobias Grosser }
24198fc6cdfbSTobias Grosser 
24208fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() {
24218fc6cdfbSTobias Grosser   if (Arch != GPUArch::NVPTX64)
24228fc6cdfbSTobias Grosser     return;
24238fc6cdfbSTobias Grosser 
24248fc6cdfbSTobias Grosser   if (requiresCUDALibDevice()) {
24258fc6cdfbSTobias Grosser     SMDiagnostic Error;
24268fc6cdfbSTobias Grosser 
24278fc6cdfbSTobias Grosser     errs() << CUDALibDevice << "\n";
24288fc6cdfbSTobias Grosser     auto LibDeviceModule =
24298fc6cdfbSTobias Grosser         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
24308fc6cdfbSTobias Grosser 
24318fc6cdfbSTobias Grosser     if (!LibDeviceModule) {
24328fc6cdfbSTobias Grosser       BuildSuccessful = false;
24338fc6cdfbSTobias Grosser       report_fatal_error("Could not find or load libdevice. Skipping GPU "
24348fc6cdfbSTobias Grosser                          "kernel generation. Please set -polly-acc-libdevice "
24358fc6cdfbSTobias Grosser                          "accordingly.\n");
24368fc6cdfbSTobias Grosser       return;
24378fc6cdfbSTobias Grosser     }
24388fc6cdfbSTobias Grosser 
24398fc6cdfbSTobias Grosser     Linker L(*GPUModule);
24408fc6cdfbSTobias Grosser 
24418fc6cdfbSTobias Grosser     // Set an nvptx64 target triple to avoid linker warnings. The original
24428fc6cdfbSTobias Grosser     // triple of the libdevice files are nvptx-unknown-unknown.
24438fc6cdfbSTobias Grosser     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
24448fc6cdfbSTobias Grosser     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
24458fc6cdfbSTobias Grosser   }
24468fc6cdfbSTobias Grosser }
24478fc6cdfbSTobias Grosser 
244857793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
244965d7f72fSSiddharth Bhat 
24505857b701STobias Grosser   if (verifyModule(*GPUModule)) {
2451349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
245265d7f72fSSiddharth Bhat                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2453349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2454a0fb8b23SSiddharth Bhat                verifyModule(*GPUModule, &dbgs()););
245565d7f72fSSiddharth Bhat 
245665d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
245765d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
245865d7f72fSSiddharth Bhat 
24595857b701STobias Grosser     BuildSuccessful = false;
24605857b701STobias Grosser     return "";
24615857b701STobias Grosser   }
246232837fe3STobias Grosser 
24638fc6cdfbSTobias Grosser   addCUDALibDevice();
24648fc6cdfbSTobias Grosser 
246532837fe3STobias Grosser   if (DumpKernelIR)
246632837fe3STobias Grosser     outs() << *GPUModule << "\n";
246732837fe3STobias Grosser 
24682f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
24699a18d559STobias Grosser     // Optimize module.
24709a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
24719a18d559STobias Grosser     PassManagerBuilder PassBuilder;
24729a18d559STobias Grosser     PassBuilder.OptLevel = 3;
24739a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
24749a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
24759a18d559STobias Grosser     OptPasses.run(*GPUModule);
24762f3073b5SPhilipp Schaad   }
24779a18d559STobias Grosser 
247874dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
247974dc3cb4STobias Grosser 
248074dc3cb4STobias Grosser   if (DumpKernelASM)
248174dc3cb4STobias Grosser     outs() << Assembly << "\n";
248274dc3cb4STobias Grosser 
248332837fe3STobias Grosser   GPUModule.release();
2484472f9654STobias Grosser   KernelIDs.clear();
248557793596STobias Grosser 
248657793596STobias Grosser   return Assembly;
248732837fe3STobias Grosser }
2488eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2489eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an
2490eadf76d3SSiddharth Bhat ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2491eadf76d3SSiddharth Bhat ///               all the isl_pw_aff are used up by this function.
2492eadf76d3SSiddharth Bhat ///
2493eadf76d3SSiddharth Bhat /// @returns  The `isl_pw_aff_list`.
2494eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list *
2495eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context,
2496eadf76d3SSiddharth Bhat                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2497eadf76d3SSiddharth Bhat   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2498eadf76d3SSiddharth Bhat 
2499eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2500eadf76d3SSiddharth Bhat     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2501eadf76d3SSiddharth Bhat   }
2502eadf76d3SSiddharth Bhat   return List;
2503eadf76d3SSiddharth Bhat }
2504eadf76d3SSiddharth Bhat 
2505eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions.
2506eadf76d3SSiddharth Bhat ///
2507eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to
2508eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the
2509eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2510eadf76d3SSiddharth Bhat /// with the given `SeedSpace`.
2511eadf76d3SSiddharth Bhat /// @param PwAffs    The list of piecewise affine functions we want to align.
2512eadf76d3SSiddharth Bhat ///                  This is an rvalue reference because the entire vector is
2513eadf76d3SSiddharth Bhat ///                  used up by the end of the operation.
2514eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with.
2515eadf76d3SSiddharth Bhat /// @returns         A std::pair, whose first element is the aligned space,
2516eadf76d3SSiddharth Bhat ///                  whose second element is the vector of aligned piecewise
2517eadf76d3SSiddharth Bhat ///                  affines.
2518eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2519eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2520eadf76d3SSiddharth Bhat             __isl_take isl_space *SeedSpace) {
2521eadf76d3SSiddharth Bhat   assert(SeedSpace && "Invalid seed space given.");
2522eadf76d3SSiddharth Bhat 
2523eadf76d3SSiddharth Bhat   isl_space *AlignSpace = SeedSpace;
2524eadf76d3SSiddharth Bhat   for (isl_pw_aff *PwAff : PwAffs) {
2525eadf76d3SSiddharth Bhat     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2526eadf76d3SSiddharth Bhat     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2527eadf76d3SSiddharth Bhat   }
2528eadf76d3SSiddharth Bhat   std::vector<isl_pw_aff *> AdjustedPwAffs;
2529eadf76d3SSiddharth Bhat 
2530eadf76d3SSiddharth Bhat   for (unsigned i = 0; i < PwAffs.size(); i++) {
2531eadf76d3SSiddharth Bhat     isl_pw_aff *Adjusted = PwAffs[i];
2532eadf76d3SSiddharth Bhat     assert(Adjusted && "Invalid pw_aff given.");
2533eadf76d3SSiddharth Bhat     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2534eadf76d3SSiddharth Bhat     AdjustedPwAffs.push_back(Adjusted);
2535eadf76d3SSiddharth Bhat   }
2536eadf76d3SSiddharth Bhat   return std::make_pair(AlignSpace, AdjustedPwAffs);
2537eadf76d3SSiddharth Bhat }
253832837fe3STobias Grosser 
25399dfe4e7cSTobias Grosser namespace {
25409dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
25419dfe4e7cSTobias Grosser public:
25429dfe4e7cSTobias Grosser   static char ID;
25439dfe4e7cSTobias Grosser 
254417f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
254517f01968SSiddharth Bhat 
254617f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
254717f01968SSiddharth Bhat 
2548e938517eSTobias Grosser   /// The scop that is currently processed.
2549e938517eSTobias Grosser   Scop *S;
2550e938517eSTobias Grosser 
255138fc0aedSTobias Grosser   LoopInfo *LI;
255238fc0aedSTobias Grosser   DominatorTree *DT;
255338fc0aedSTobias Grosser   ScalarEvolution *SE;
255438fc0aedSTobias Grosser   const DataLayout *DL;
255538fc0aedSTobias Grosser   RegionInfo *RI;
255638fc0aedSTobias Grosser 
25579dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
25589dfe4e7cSTobias Grosser 
2559e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2560e938517eSTobias Grosser   ///
2561e938517eSTobias Grosser   /// @returns The compilation options.
2562e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2563e938517eSTobias Grosser     auto DebugOptions =
2564e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2565e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2566e938517eSTobias Grosser 
2567e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2568e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2569e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2570e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
25718950ceadSTobias Grosser     DebugOptions->verbose = false;
2572e938517eSTobias Grosser 
2573e938517eSTobias Grosser     Options->debug = DebugOptions;
2574e938517eSTobias Grosser 
25759e3db2b7SSiddharth Bhat     Options->group_chains = false;
2576e938517eSTobias Grosser     Options->reschedule = true;
2577e938517eSTobias Grosser     Options->scale_tile_loops = false;
2578e938517eSTobias Grosser     Options->wrap = false;
2579e938517eSTobias Grosser 
2580e938517eSTobias Grosser     Options->non_negative_parameters = false;
2581e938517eSTobias Grosser     Options->ctx = nullptr;
2582e938517eSTobias Grosser     Options->sizes = nullptr;
2583e938517eSTobias Grosser 
25849e3db2b7SSiddharth Bhat     Options->tile = true;
25854eaedde5STobias Grosser     Options->tile_size = 32;
25864eaedde5STobias Grosser 
25879e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
25889e3db2b7SSiddharth Bhat 
2589130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2590b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2591b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2592e938517eSTobias Grosser 
2593e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2594e938517eSTobias Grosser     Options->openmp = false;
2595e938517eSTobias Grosser     Options->linearize_device_arrays = true;
25969e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2597e938517eSTobias Grosser 
25989e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
25999e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
26009e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26019e3db2b7SSiddharth Bhat 
26029e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
26039e3db2b7SSiddharth Bhat     Options->hybrid = false;
2604e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2605e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2606e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2607e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2608e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2609e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2610e938517eSTobias Grosser 
2611e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2612e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2613e938517eSTobias Grosser 
2614e938517eSTobias Grosser     return Options;
2615e938517eSTobias Grosser   }
2616e938517eSTobias Grosser 
2617f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2618f384594dSTobias Grosser   ///
2619f384594dSTobias Grosser   /// Instead of a normal access of the form:
2620f384594dSTobias Grosser   ///
2621f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2622f384594dSTobias Grosser   ///
2623f384594dSTobias Grosser   /// a tagged access has the form
2624f384594dSTobias Grosser   ///
2625f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2626f384594dSTobias Grosser   ///
2627f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2628f384594dSTobias Grosser   /// triggered the access.
2629f384594dSTobias Grosser   ///
2630f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2631f384594dSTobias Grosser   ///
2632f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2633f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2634b65ccc43STobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2635f384594dSTobias Grosser 
2636f384594dSTobias Grosser     for (auto &Stmt : *S)
2637f384594dSTobias Grosser       for (auto &Acc : Stmt)
2638f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
26391515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2640dcf8d696STobias Grosser           Relation =
2641dcf8d696STobias Grosser               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2642f384594dSTobias Grosser 
2643f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2644f384594dSTobias Grosser           Space = isl_space_range(Space);
2645f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2646fe46c3ffSTobias Grosser           Space =
2647fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2648f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2649f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2650f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2651f384594dSTobias Grosser         }
2652f384594dSTobias Grosser 
2653f384594dSTobias Grosser     return Accesses;
2654f384594dSTobias Grosser   }
2655f384594dSTobias Grosser 
2656f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2657f384594dSTobias Grosser   ///
2658f384594dSTobias Grosser   /// @see getTaggedAccesses
2659f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2660f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2661f384594dSTobias Grosser   }
2662f384594dSTobias Grosser 
2663f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2664f384594dSTobias Grosser   ///
2665f384594dSTobias Grosser   /// @see getTaggedAccesses
2666f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2667f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2668f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2669f384594dSTobias Grosser   }
2670f384594dSTobias Grosser 
2671f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2672f384594dSTobias Grosser   ///
2673f384594dSTobias Grosser   /// @see getTaggedAccesses
2674f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2675f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2676f384594dSTobias Grosser   }
2677f384594dSTobias Grosser 
2678aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2679aef5196fSTobias Grosser   ///
2680aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2681aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2682aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2683aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2684aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2685aef5196fSTobias Grosser   /// the data format that ppcg expects.
2686aef5196fSTobias Grosser   ///
2687aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2688aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2689aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
269000fd43b3SPhilip Pfaffe         S->getIslCtx().get(),
2691bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
269200fd43b3SPhilip Pfaffe     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2693aef5196fSTobias Grosser 
269425271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
26959a63570bSTobias Grosser       isl_id *Id = S->getIdForParam(P).release();
2696aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2697aef5196fSTobias Grosser     }
2698aef5196fSTobias Grosser 
2699aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
270077eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2701aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2702aef5196fSTobias Grosser     }
2703aef5196fSTobias Grosser 
2704aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2705aef5196fSTobias Grosser 
2706aef5196fSTobias Grosser     return Names;
2707aef5196fSTobias Grosser   }
2708aef5196fSTobias Grosser 
2709e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2710e938517eSTobias Grosser   ///
2711f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2712f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2713f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2714f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2715e938517eSTobias Grosser   ///
2716e938517eSTobias Grosser   /// @returns A new ppcg scop.
2717e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
27189e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
27199e3db2b7SSiddharth Bhat 
2720e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2721e938517eSTobias Grosser 
2722e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2723a82f2d26SSiddharth Bhat     // enable live range reordering
2724a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2725e938517eSTobias Grosser 
2726e938517eSTobias Grosser     PPCGScop->start = 0;
2727e938517eSTobias Grosser     PPCGScop->end = 0;
2728e938517eSTobias Grosser 
27298ea1fc19STobias Grosser     PPCGScop->context = S->getContext().release();
273031df6f31STobias Grosser     PPCGScop->domain = S->getDomains().release();
27319e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
27328ea1fc19STobias Grosser     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2733f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
27345ab39ff2STobias Grosser     PPCGScop->reads = S->getReads().release();
2735e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2736f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
27375ab39ff2STobias Grosser     PPCGScop->may_writes = S->getWrites().release();
2738f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
27395ab39ff2STobias Grosser     PPCGScop->must_writes = S->getMustWrites().release();
2740e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
27418dae41a1STobias Grosser     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
27428dae41a1STobias Grosser     PPCGScop->must_kills = KillsInfo.MustKills.release();
27439e3db2b7SSiddharth Bhat 
2744e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2745a82f2d26SSiddharth Bhat     PPCGScop->independence =
2746a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2747e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2748e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2749e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2750e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2751e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2752e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2753e938517eSTobias Grosser 
275461bd3a48STobias Grosser     PPCGScop->schedule = S->getScheduleTree().release();
2755a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2756a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2757a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
27588dae41a1STobias Grosser           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2759a82f2d26SSiddharth Bhat 
2760a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2761e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2762e938517eSTobias Grosser 
2763f384594dSTobias Grosser     compute_tagger(PPCGScop);
2764f384594dSTobias Grosser     compute_dependences(PPCGScop);
27659e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2766f384594dSTobias Grosser 
2767e938517eSTobias Grosser     return PPCGScop;
2768e938517eSTobias Grosser   }
2769e938517eSTobias Grosser 
2770a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
277160f63b49STobias Grosser   ///
277260f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
277360f63b49STobias Grosser   ///
277460f63b49STobias Grosser   /// @returns A list of array accesses.
277560f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
277660f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
277760f63b49STobias Grosser 
277860f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
277900fd43b3SPhilip Pfaffe       auto Access =
278000fd43b3SPhilip Pfaffe           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
278160f63b49STobias Grosser       Access->read = Acc->isRead();
278260f63b49STobias Grosser       Access->write = Acc->isWrite();
27831515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
278460f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
278560f63b49STobias Grosser       Space = isl_space_range(Space);
278660f63b49STobias Grosser       Space = isl_space_from_range(Space);
2787fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
278860f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
278960f63b49STobias Grosser       Access->tagged_access =
27901515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2791b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2792fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
279360f63b49STobias Grosser       Access->next = Accesses;
2794b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2795ecb94a03STobias Grosser       // TODO: Also mark one-element accesses to arrays as fixed-element.
2796ecb94a03STobias Grosser       Access->fixed_element =
2797ecb94a03STobias Grosser           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
279860f63b49STobias Grosser       Accesses = Access;
279960f63b49STobias Grosser     }
280060f63b49STobias Grosser 
280160f63b49STobias Grosser     return Accesses;
280260f63b49STobias Grosser   }
280360f63b49STobias Grosser 
280469b46751STobias Grosser   /// Collect the list of GPU statements.
280569b46751STobias Grosser   ///
280669b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
280769b46751STobias Grosser   /// as well as a list with all memory accesses.
280869b46751STobias Grosser   ///
280969b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
281069b46751STobias Grosser   ///
281169b46751STobias Grosser   /// @returns A linked-list of statements.
281269b46751STobias Grosser   gpu_stmt *getStatements() {
281300fd43b3SPhilip Pfaffe     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
281469b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
281569b46751STobias Grosser 
281669b46751STobias Grosser     int i = 0;
281769b46751STobias Grosser     for (auto &Stmt : *S) {
281869b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
281969b46751STobias Grosser 
2820dcf8d696STobias Grosser       GPUStmt->id = Stmt.getDomainId().release();
282169b46751STobias Grosser 
282269b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
282369b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
282460f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
282569b46751STobias Grosser       i++;
282669b46751STobias Grosser     }
282769b46751STobias Grosser 
282869b46751STobias Grosser     return Stmts;
282969b46751STobias Grosser   }
283069b46751STobias Grosser 
283160f63b49STobias Grosser   /// Derive the extent of an array.
283260f63b49STobias Grosser   ///
2833d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2834d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2835d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2836d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2837d58acf86STobias Grosser   /// subscript value for the first dimension.
283860f63b49STobias Grosser   ///
283960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
284060f63b49STobias Grosser   ///
284160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
2842d2e57981STobias Grosser   isl::set getExtent(ScopArrayInfo *Array) {
2843d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
2844fa03cb76STobias Grosser 
2845fa03cb76STobias Grosser     if (Array->getNumberOfDimensions() == 0)
2846fa03cb76STobias Grosser       return isl::set::universe(Array->getSpace());
2847fa03cb76STobias Grosser 
2848fa03cb76STobias Grosser     isl::union_map Accesses = S->getAccesses(Array);
2849d2e57981STobias Grosser     isl::union_set AccessUSet = Accesses.range();
2850d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2851d2e57981STobias Grosser     AccessUSet = AccessUSet.detect_equalities();
2852d2e57981STobias Grosser     AccessUSet = AccessUSet.coalesce();
2853d58acf86STobias Grosser 
2854d2e57981STobias Grosser     if (AccessUSet.is_empty())
2855d2e57981STobias Grosser       return isl::set::empty(Array->getSpace());
2856d58acf86STobias Grosser 
2857d2e57981STobias Grosser     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
285860f63b49STobias Grosser 
2859d2e57981STobias Grosser     isl::local_space LS = isl::local_space(Array->getSpace());
2860d58acf86STobias Grosser 
2861d2e57981STobias Grosser     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2862d2e57981STobias Grosser     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2863d2e57981STobias Grosser     isl::pw_aff OuterMax = AccessSet.dim_max(0);
2864d2e57981STobias Grosser     OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2865d2e57981STobias Grosser     OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2866d2e57981STobias Grosser     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2867d2e57981STobias Grosser     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2868d58acf86STobias Grosser 
2869d2e57981STobias Grosser     isl::set Extent = isl::set::universe(Array->getSpace());
2870d58acf86STobias Grosser 
2871d2e57981STobias Grosser     Extent = Extent.intersect(OuterMin.le_set(Val));
2872d2e57981STobias Grosser     Extent = Extent.intersect(OuterMax.ge_set(Val));
2873d58acf86STobias Grosser 
2874d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2875d2e57981STobias Grosser       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2876d58acf86STobias Grosser 
2877b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2878d2e57981STobias Grosser       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2879b7f68b8cSSiddharth Bhat 
2880b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2881b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2882d2e57981STobias Grosser       if (PwAff.is_null()) {
2883b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2884b7f68b8cSSiddharth Bhat         continue;
2885b7f68b8cSSiddharth Bhat       }
2886b7f68b8cSSiddharth Bhat 
2887d2e57981STobias Grosser       isl::pw_aff Val = isl::aff::var_on_domain(
2888d2e57981STobias Grosser           isl::local_space(Array->getSpace()), isl::dim::set, i);
2889d2e57981STobias Grosser       PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2890d2e57981STobias Grosser       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2891d2e57981STobias Grosser       isl::set Set = PwAff.gt_set(Val);
2892d2e57981STobias Grosser       Extent = Set.intersect(Extent);
2893d58acf86STobias Grosser     }
2894d58acf86STobias Grosser 
2895d58acf86STobias Grosser     return Extent;
289660f63b49STobias Grosser   }
289760f63b49STobias Grosser 
289860f63b49STobias Grosser   /// Derive the bounds of an array.
289960f63b49STobias Grosser   ///
290060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
290160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
290260f63b49STobias Grosser   /// ScopArrayInfo.
290360f63b49STobias Grosser   ///
290460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
290560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
290660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2907eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> Bounds;
29089e3db2b7SSiddharth Bhat 
290960f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
291002293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
291102293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
291202293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
291302293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
291402293ed7STobias Grosser         isl_set_free(Dom);
29159e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2916eadf76d3SSiddharth Bhat         Bounds.push_back(Zero);
291702293ed7STobias Grosser       } else {
291860f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
291960f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
292060f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
292160f63b49STobias Grosser         isl_set_free(Dom);
292260f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
292302293ed7STobias Grosser         isl_local_space *LS =
292402293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
292560f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
292660f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
292760f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
29288ea1fc19STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2929eadf76d3SSiddharth Bhat         Bounds.push_back(Bound);
293060f63b49STobias Grosser       }
293102293ed7STobias Grosser     }
293260f63b49STobias Grosser 
293360f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
293477eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
293560f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
293660f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
2937e2950f46SSiddharth Bhat 
2938e2950f46SSiddharth Bhat       // We need types to work out, which is why we perform this weird dance
2939e2950f46SSiddharth Bhat       // with `Aff` and `Bound`. Consider this example:
2940e2950f46SSiddharth Bhat 
2941e2950f46SSiddharth Bhat       // LS: [p] -> { [] }
2942e2950f46SSiddharth Bhat       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2943e2950f46SSiddharth Bhat       // This `~` is used to denote a "null space" (which is different from
2944e2950f46SSiddharth Bhat       // a *zero dimensional* space), which is something that ISL does not
2945e2950f46SSiddharth Bhat       // show you when pretty printing.
2946e2950f46SSiddharth Bhat 
2947e2950f46SSiddharth Bhat       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2948e2950f46SSiddharth Bhat       // space, not a "null space" which does not exist at all.
2949e2950f46SSiddharth Bhat 
2950e2950f46SSiddharth Bhat       // When we pullback (precompose) `Bound` with `Zero`, we get:
2951e2950f46SSiddharth Bhat       // Bound . Zero =
2952e2950f46SSiddharth Bhat       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2953e2950f46SSiddharth Bhat       //     [p] -> { ~ -> [(10p)] } =
2954e2950f46SSiddharth Bhat       //     [p] -> [(10p)] (as ISL pretty prints it)
2955e2950f46SSiddharth Bhat       // Bound Pullback: [p] -> { [(10p)] }
2956e2950f46SSiddharth Bhat 
2957e2950f46SSiddharth Bhat       // We want this kind of an expression for Bound, without a
2958e2950f46SSiddharth Bhat       // zero dimensional input, but with a "null space" input for the types
2959e2950f46SSiddharth Bhat       // to work out later on, as far as I (Siddharth Bhat) understand.
2960e2950f46SSiddharth Bhat       // I was unable to find a reference to this in the ISL manual.
2961e2950f46SSiddharth Bhat       // References: Tobias Grosser.
2962e2950f46SSiddharth Bhat 
296360f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2964eadf76d3SSiddharth Bhat       Bounds.push_back(Bound);
296560f63b49STobias Grosser     }
29669e3db2b7SSiddharth Bhat 
2967eadf76d3SSiddharth Bhat     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2968eadf76d3SSiddharth Bhat     /// to have the same parameter dimensions. So, we need to align them to an
2969eadf76d3SSiddharth Bhat     /// appropriate space.
2970eadf76d3SSiddharth Bhat     /// Scop::Context is _not_ an appropriate space, because when we have
2971eadf76d3SSiddharth Bhat     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2972eadf76d3SSiddharth Bhat     /// contain all parameter dimensions.
2973eadf76d3SSiddharth Bhat     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2974b65ccc43STobias Grosser     isl_space *SeedAlignSpace = S->getParamSpace().release();
2975eadf76d3SSiddharth Bhat     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2976eadf76d3SSiddharth Bhat 
2977eadf76d3SSiddharth Bhat     isl_space *AlignSpace = nullptr;
2978eadf76d3SSiddharth Bhat     std::vector<isl_pw_aff *> AlignedBounds;
2979eadf76d3SSiddharth Bhat     std::tie(AlignSpace, AlignedBounds) =
2980eadf76d3SSiddharth Bhat         alignPwAffs(std::move(Bounds), SeedAlignSpace);
2981eadf76d3SSiddharth Bhat 
2982eadf76d3SSiddharth Bhat     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
2983eadf76d3SSiddharth Bhat 
2984eadf76d3SSiddharth Bhat     isl_pw_aff_list *BoundsList =
298500fd43b3SPhilip Pfaffe         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
2986eadf76d3SSiddharth Bhat 
29879e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2988eadf76d3SSiddharth Bhat     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
29899e3db2b7SSiddharth Bhat 
29909e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
29919e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
29929e3db2b7SSiddharth Bhat 
29939e3db2b7SSiddharth Bhat     PPCGArray.bound =
29949e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
29959e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
299660f63b49STobias Grosser   }
299760f63b49STobias Grosser 
299860f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
299960f63b49STobias Grosser   ///
300060f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
300143f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
300243f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
300360f63b49STobias Grosser     int i = 0;
300443f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
300560f63b49STobias Grosser       std::string TypeName;
300660f63b49STobias Grosser       raw_string_ostream OS(TypeName);
300760f63b49STobias Grosser 
300860f63b49STobias Grosser       OS << *Array->getElementType();
300960f63b49STobias Grosser       TypeName = OS.str();
301060f63b49STobias Grosser 
301160f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
301260f63b49STobias Grosser 
301377eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
301460f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
301534eeabbcSSiddharth Bhat       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
301660f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
301760f63b49STobias Grosser       PPCGArray.extent = nullptr;
301860f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
3019d2e57981STobias Grosser       PPCGArray.extent = getExtent(Array).release();
302060f63b49STobias Grosser       PPCGArray.n_ref = 0;
302160f63b49STobias Grosser       PPCGArray.refs = nullptr;
302260f63b49STobias Grosser       PPCGArray.accessed = true;
3023fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
3024fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
302560f63b49STobias Grosser       PPCGArray.has_compound_element = false;
302660f63b49STobias Grosser       PPCGArray.local = false;
302760f63b49STobias Grosser       PPCGArray.declare_local = false;
302860f63b49STobias Grosser       PPCGArray.global = false;
302960f63b49STobias Grosser       PPCGArray.linearize = false;
303060f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
303113c78e4dSTobias Grosser       PPCGArray.user = Array;
303260f63b49STobias Grosser 
30339e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
303460f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
30352d010dafSTobias Grosser       i++;
3036b9fc860aSTobias Grosser 
3037b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
3038ecb94a03STobias Grosser       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
303960f63b49STobias Grosser     }
304060f63b49STobias Grosser   }
304160f63b49STobias Grosser 
304260f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
304360f63b49STobias Grosser   ///
304460f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
304560f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
3046b65ccc43STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
304760f63b49STobias Grosser 
3048d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
304977eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
305060f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
305160f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
305260f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
305360f63b49STobias Grosser     }
305460f63b49STobias Grosser 
305560f63b49STobias Grosser     return Maps;
305660f63b49STobias Grosser   }
305760f63b49STobias Grosser 
3058e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
3059e938517eSTobias Grosser   ///
3060a6d48f59SMichael Kruse   /// @returns A new gpu program description.
3061e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3062e938517eSTobias Grosser 
3063e938517eSTobias Grosser     if (!PPCGScop)
3064e938517eSTobias Grosser       return nullptr;
3065e938517eSTobias Grosser 
306600fd43b3SPhilip Pfaffe     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3067e938517eSTobias Grosser 
306800fd43b3SPhilip Pfaffe     PPCGProg->ctx = S->getIslCtx().get();
3069e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
3070aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
307160f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
307260f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
307360f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
307460f63b49STobias Grosser     PPCGProg->tagged_must_kill =
307560f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
307660f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
307760f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
30789e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
3079e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
308069b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
308169b46751STobias Grosser     PPCGProg->stmts = getStatements();
308243f178bbSSiddharth Bhat 
308343f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
308443f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
308543f178bbSSiddharth Bhat     // empty arrays:
308643f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
308743f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
308843f178bbSSiddharth Bhat     auto ValidSAIsRange =
308943f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3090d2e57981STobias Grosser           return !getExtent(SAI).is_empty();
309143f178bbSSiddharth Bhat         });
309243f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
309343f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
309443f178bbSSiddharth Bhat 
309543f178bbSSiddharth Bhat     PPCGProg->n_array =
309643f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
309758166b13SMichael Kruse     PPCGProg->array = isl_calloc_array(
309858166b13SMichael Kruse         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
309960f63b49STobias Grosser 
310043f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
3101e938517eSTobias Grosser 
3102ecb94a03STobias Grosser     PPCGProg->array_order = nullptr;
3103ecb94a03STobias Grosser     collect_order_dependences(PPCGProg);
3104ecb94a03STobias Grosser 
3105d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3106e938517eSTobias Grosser     return PPCGProg;
3107e938517eSTobias Grosser   }
3108e938517eSTobias Grosser 
310969b46751STobias Grosser   struct PrintGPUUserData {
311069b46751STobias Grosser     struct cuda_info *CudaInfo;
311169b46751STobias Grosser     struct gpu_prog *PPCGProg;
311269b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
311369b46751STobias Grosser   };
311469b46751STobias Grosser 
311569b46751STobias Grosser   /// Print a user statement node in the host code.
311669b46751STobias Grosser   ///
311769b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
311869b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
311969b46751STobias Grosser   /// host ast.
312069b46751STobias Grosser   ///
312169b46751STobias Grosser   /// @param P The printer to print to
312269b46751STobias Grosser   /// @param Options The printing options to use
312369b46751STobias Grosser   /// @param Node The node to print
312469b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
312569b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
312669b46751STobias Grosser   ///
312769b46751STobias Grosser   /// @returns A printer to which the output has been printed.
312869b46751STobias Grosser   static __isl_give isl_printer *
312969b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
313069b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
313169b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
313269b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
313369b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
313469b46751STobias Grosser 
313569b46751STobias Grosser     if (Id) {
313620251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
313720251734STobias Grosser 
313820251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
313920251734STobias Grosser       // otherwise try to call pet functionality that is not available in
314020251734STobias Grosser       // Polly.
314120251734STobias Grosser       if (IsUser) {
314220251734STobias Grosser         P = isl_printer_start_line(P);
314320251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
314420251734STobias Grosser         P = isl_printer_end_line(P);
314520251734STobias Grosser         isl_id_free(Id);
314620251734STobias Grosser         isl_ast_print_options_free(Options);
314720251734STobias Grosser         return P;
314820251734STobias Grosser       }
314920251734STobias Grosser 
315069b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
315169b46751STobias Grosser       isl_id_free(Id);
315269b46751STobias Grosser       Data->Kernels.push_back(Kernel);
315369b46751STobias Grosser     }
315469b46751STobias Grosser 
315569b46751STobias Grosser     return print_host_user(P, Options, Node, User);
315669b46751STobias Grosser   }
315769b46751STobias Grosser 
315869b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
315969b46751STobias Grosser   ///
316069b46751STobias Grosser   /// @param Kernel The kernel to print
316169b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
316200fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
316369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
316400fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
316569b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
316669b46751STobias Grosser     char *String = isl_printer_get_str(P);
3167936c74adSSiddharth Bhat     outs() << String << "\n";
316869b46751STobias Grosser     free(String);
316969b46751STobias Grosser     isl_printer_free(P);
317069b46751STobias Grosser   }
317169b46751STobias Grosser 
317269b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
317369b46751STobias Grosser   ///
317469b46751STobias Grosser   /// @param Tree An AST describing GPU code
317569b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
317669b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
317700fd43b3SPhilip Pfaffe     auto *P = isl_printer_to_str(S->getIslCtx().get());
317869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
317969b46751STobias Grosser 
318069b46751STobias Grosser     PrintGPUUserData Data;
318169b46751STobias Grosser     Data.PPCGProg = PPCGProg;
318269b46751STobias Grosser 
318300fd43b3SPhilip Pfaffe     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
318469b46751STobias Grosser     Options =
318569b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
318669b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
318769b46751STobias Grosser     char *String = isl_printer_get_str(P);
3188936c74adSSiddharth Bhat     outs() << "# host\n";
3189936c74adSSiddharth Bhat     outs() << String << "\n";
319069b46751STobias Grosser     free(String);
319169b46751STobias Grosser     isl_printer_free(P);
319269b46751STobias Grosser 
319369b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
3194936c74adSSiddharth Bhat       outs() << "# kernel" << Kernel->id << "\n";
319569b46751STobias Grosser       printKernel(Kernel);
319669b46751STobias Grosser     }
319769b46751STobias Grosser   }
319869b46751STobias Grosser 
3199f384594dSTobias Grosser   // Generate a GPU program using PPCG.
3200f384594dSTobias Grosser   //
3201f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
3202f384594dSTobias Grosser   //
3203f384594dSTobias Grosser   //  1) Compute new schedule for the program.
3204f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
3205f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
3206f384594dSTobias Grosser   //
3207f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3208f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3209f384594dSTobias Grosser   // strategy directly from this pass.
3210f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3211f384594dSTobias Grosser 
321200fd43b3SPhilip Pfaffe     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3213f384594dSTobias Grosser 
321400fd43b3SPhilip Pfaffe     PPCGGen->ctx = S->getIslCtx().get();
3215f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
3216f384594dSTobias Grosser     PPCGGen->print = nullptr;
3217f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
321860c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3219f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
3220f384594dSTobias Grosser     PPCGGen->tree = nullptr;
3221f384594dSTobias Grosser     PPCGGen->types.n = 0;
3222f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
3223f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
3224f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
3225f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
3226f384594dSTobias Grosser 
3227f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
3228f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3229f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
32302341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3231f384594dSTobias Grosser 
3232f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
3233f384594dSTobias Grosser 
3234e32498c9STobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
3235e32498c9STobias Grosser 
3236b5563c68STobias Grosser     Schedule =
3237b5563c68STobias Grosser         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3238b5563c68STobias Grosser 
323969b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
3240aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
3241349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3242638316daSSiddharth Bhat                         << " does not have permutable bands. Bailing out\n";);
324369b46751STobias Grosser     } else {
3244861a387fSTobias Grosser       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3245861a387fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
324669b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
324769b46751STobias Grosser     }
3248aef5196fSTobias Grosser 
3249f384594dSTobias Grosser     if (DumpSchedule) {
325000fd43b3SPhilip Pfaffe       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3251f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3252f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
3253f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
3254f384594dSTobias Grosser       if (Schedule)
3255f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
3256f384594dSTobias Grosser       else
3257f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
3258f384594dSTobias Grosser 
3259936c74adSSiddharth Bhat       outs() << isl_printer_get_str(P) << "\n";
3260f384594dSTobias Grosser       isl_printer_free(P);
3261f384594dSTobias Grosser     }
3262f384594dSTobias Grosser 
326369b46751STobias Grosser     if (DumpCode) {
3264936c74adSSiddharth Bhat       outs() << "Code\n";
3265936c74adSSiddharth Bhat       outs() << "====\n";
326669b46751STobias Grosser       if (PPCGGen->tree)
326769b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
326869b46751STobias Grosser       else
3269936c74adSSiddharth Bhat         outs() << "No code generated\n";
327069b46751STobias Grosser     }
327169b46751STobias Grosser 
3272f384594dSTobias Grosser     isl_schedule_free(Schedule);
3273f384594dSTobias Grosser 
3274f384594dSTobias Grosser     return PPCGGen;
3275f384594dSTobias Grosser   }
3276f384594dSTobias Grosser 
3277f384594dSTobias Grosser   /// Free gpu_gen structure.
3278f384594dSTobias Grosser   ///
3279f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
3280f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
3281f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
3282f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
3283f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
3284f384594dSTobias Grosser     free(PPCGGen);
3285f384594dSTobias Grosser   }
3286f384594dSTobias Grosser 
3287b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
3288b307ed4dSTobias Grosser   ///
3289b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3290b307ed4dSTobias Grosser   /// ourselves.
3291b307ed4dSTobias Grosser   ///
3292b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3293b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3294b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3295b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3296b307ed4dSTobias Grosser     free(PPCGScop->options);
3297b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3298b307ed4dSTobias Grosser   }
3299b307ed4dSTobias Grosser 
330082f2af35STobias Grosser   /// Approximate the number of points in the set.
330182f2af35STobias Grosser   ///
330282f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
330382f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
330482f2af35STobias Grosser   ///
330582f2af35STobias Grosser   /// @param Set   The set to count.
330682f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
330782f2af35STobias Grosser   ///              expression.
330882f2af35STobias Grosser   ///
330982f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
331082f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
331182f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
331282f2af35STobias Grosser 
331382f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
331482f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
331582f2af35STobias Grosser 
331682f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
331782f2af35STobias Grosser     Space = isl_space_params(Space);
331882f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
331982f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
332082f2af35STobias Grosser 
33213044dc51SMichael Kruse     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
332282f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
332382f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
332482f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
332582f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
332682f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
332782f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
332882f2af35STobias Grosser     }
332982f2af35STobias Grosser 
333082f2af35STobias Grosser     isl_set_free(Set);
333182f2af35STobias Grosser     isl_pw_aff_free(OneAff);
333282f2af35STobias Grosser 
333382f2af35STobias Grosser     return Expr;
333482f2af35STobias Grosser   }
333582f2af35STobias Grosser 
333682f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
333782f2af35STobias Grosser   /// statement.
333882f2af35STobias Grosser   ///
333982f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
334082f2af35STobias Grosser   ///              instructions.
334182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
334282f2af35STobias Grosser   ///              expression.
334382f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
334482f2af35STobias Grosser   ///          by @p Stmt.
334582f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
334682f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
3347dcf8d696STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
334882f2af35STobias Grosser 
334982f2af35STobias Grosser     long InstCount = 0;
335082f2af35STobias Grosser 
335182f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
335282f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
335382f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
335482f2af35STobias Grosser     } else {
335582f2af35STobias Grosser       auto *R = Stmt.getRegion();
335682f2af35STobias Grosser 
335782f2af35STobias Grosser       for (auto *BB : R->blocks()) {
335882f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
335982f2af35STobias Grosser       }
336082f2af35STobias Grosser     }
336182f2af35STobias Grosser 
336200fd43b3SPhilip Pfaffe     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
336382f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
336482f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
336582f2af35STobias Grosser   }
336682f2af35STobias Grosser 
336782f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
336882f2af35STobias Grosser   ///
336982f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
337082f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
337182f2af35STobias Grosser   ///              expression.
337282f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
337382f2af35STobias Grosser   ///          in @p S.
337482f2af35STobias Grosser   __isl_give isl_ast_expr *
337582f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
337682f2af35STobias Grosser     isl_ast_expr *Instructions;
337782f2af35STobias Grosser 
337800fd43b3SPhilip Pfaffe     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
337982f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
338082f2af35STobias Grosser 
338182f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
338282f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
338382f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
338482f2af35STobias Grosser     }
338582f2af35STobias Grosser     return Instructions;
338682f2af35STobias Grosser   }
338782f2af35STobias Grosser 
338882f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
338982f2af35STobias Grosser   ///
339082f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
339182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
339282f2af35STobias Grosser   ///              expression.
339382f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
339482f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
339582f2af35STobias Grosser   __isl_give isl_ast_expr *
339682f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
339782f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
339800fd43b3SPhilip Pfaffe     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
339982f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
340082f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
340182f2af35STobias Grosser   }
340282f2af35STobias Grosser 
3403f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3404f291c8d5SSiddharth Bhat   /// kernels.
3405f291c8d5SSiddharth Bhat   ///
3406f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3407f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
34088fc6cdfbSTobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
34098fc6cdfbSTobias Grosser                                             bool AllowCUDALibDevice) {
3410f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3411f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
34128fc6cdfbSTobias Grosser       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
341378027437SSiddharth Bhat                                           AllowCUDALibDevice))
3414f291c8d5SSiddharth Bhat         continue;
3415f291c8d5SSiddharth Bhat 
341678027437SSiddharth Bhat       for (Value *Op : Inst.operands())
341778027437SSiddharth Bhat         // Look for (<func-type>*) among operands of Inst
341878027437SSiddharth Bhat         if (auto PtrTy = dyn_cast<PointerType>(Op->getType())) {
341978027437SSiddharth Bhat           if (isa<FunctionType>(PtrTy->getElementType())) {
3420349506a9SNicola Zaghen             LLVM_DEBUG(dbgs()
3421349506a9SNicola Zaghen                        << Inst << " has illegal use of function in kernel.\n");
3422bccaea57SSiddharth Bhat             return true;
3423bccaea57SSiddharth Bhat           }
3424f291c8d5SSiddharth Bhat         }
342578027437SSiddharth Bhat     }
3426bccaea57SSiddharth Bhat     return false;
3427bccaea57SSiddharth Bhat   }
3428bccaea57SSiddharth Bhat 
3429f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
34308fc6cdfbSTobias Grosser   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3431bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3432bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
34338fc6cdfbSTobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
34348fc6cdfbSTobias Grosser                                                  AllowCUDALibDevice))
3435bccaea57SSiddharth Bhat           return true;
3436bccaea57SSiddharth Bhat       } else {
3437bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3438bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3439bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
34408fc6cdfbSTobias Grosser           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3441bccaea57SSiddharth Bhat             return true;
3442bccaea57SSiddharth Bhat       }
3443bccaea57SSiddharth Bhat     }
3444bccaea57SSiddharth Bhat     return false;
3445bccaea57SSiddharth Bhat   }
3446bccaea57SSiddharth Bhat 
344738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
344838fc0aedSTobias Grosser   ///
344932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
345032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
345132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
345238fc0aedSTobias Grosser     ScopAnnotator Annotator;
345338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
345438fc0aedSTobias Grosser 
345538fc0aedSTobias Grosser     Region *R = &S->getRegion();
345638fc0aedSTobias Grosser 
345738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
345838fc0aedSTobias Grosser 
345938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
346038fc0aedSTobias Grosser 
346138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
346238fc0aedSTobias Grosser 
346338fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
346438fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
346538fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
346638fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
346738fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
346838fc0aedSTobias Grosser     // code generating this scop.
346903346c27SSiddharth Bhat     BBPair StartExitBlocks;
347003346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
347103346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
34722d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3473256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
347438fc0aedSTobias Grosser 
347503346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
347603346c27SSiddharth Bhat 
34772d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
347817f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3479acf80064SEli Friedman 
348038fc0aedSTobias Grosser     // TODO: Handle LICM
348138fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
348238fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
3483cb1aef8dSTobias Grosser 
348400fd43b3SPhilip Pfaffe     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
34852b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
348682f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
348782f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3488cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3489cb1aef8dSTobias Grosser 
34909e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
34919e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
349271dfb3ebSSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads()) {
34932fb847fbSTobias Grosser       // Patch the introduced branch condition to ensure that we always execute
34942fb847fbSTobias Grosser       // the original SCoP.
34952fb847fbSTobias Grosser       auto *FalseI1 = Builder.getFalse();
34962fb847fbSTobias Grosser       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
34972fb847fbSTobias Grosser       SplitBBTerm->setOperand(0, FalseI1);
34982fb847fbSTobias Grosser 
3499349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
35004ebeb356SSiddharth Bhat                                S->getFunction().getName() +
35014ebeb356SSiddharth Bhat                                " | Scop Region: " + S->getNameStr());
350271dfb3ebSSiddharth Bhat       // adjust the dominator tree accordingly.
350371dfb3ebSSiddharth Bhat       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
350471dfb3ebSSiddharth Bhat       assert(ExitingBlock);
350571dfb3ebSSiddharth Bhat       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
350671dfb3ebSSiddharth Bhat       assert(MergeBlock);
350771dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*StartBlock, Builder);
350871dfb3ebSSiddharth Bhat       polly::markBlockUnreachable(*ExitingBlock, Builder);
350971dfb3ebSSiddharth Bhat       auto *ExitingBB = S->getExitingBlock();
351071dfb3ebSSiddharth Bhat       assert(ExitingBB);
35119e3db2b7SSiddharth Bhat 
351271dfb3ebSSiddharth Bhat       DT->changeImmediateDominator(MergeBlock, ExitingBB);
351371dfb3ebSSiddharth Bhat       DT->eraseNode(ExitingBlock);
351471dfb3ebSSiddharth Bhat       isl_ast_expr_free(Condition);
351571dfb3ebSSiddharth Bhat       isl_ast_node_free(Root);
351671dfb3ebSSiddharth Bhat     } else {
351771dfb3ebSSiddharth Bhat 
35187b9f5ca2SSiddharth Bhat       if (polly::PerfMonitoring) {
35197b9f5ca2SSiddharth Bhat         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
35207b9f5ca2SSiddharth Bhat         P.initialize();
35217b9f5ca2SSiddharth Bhat         P.insertRegionStart(SplitBlock->getTerminator());
35227b9f5ca2SSiddharth Bhat 
35237b9f5ca2SSiddharth Bhat         // TODO: actually think if this is the correct exiting block to place
35247b9f5ca2SSiddharth Bhat         // the `end` performance marker. Invariant load hoisting changes
35257b9f5ca2SSiddharth Bhat         // the CFG in a way that I do not precisely understand, so I
35267b9f5ca2SSiddharth Bhat         // (Siddharth<[email protected]>) should come back to this and
35277b9f5ca2SSiddharth Bhat         // think about which exiting block to use.
35287b9f5ca2SSiddharth Bhat         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
35297b9f5ca2SSiddharth Bhat         assert(ExitingBlock);
35307b9f5ca2SSiddharth Bhat         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
35317b9f5ca2SSiddharth Bhat         P.insertRegionEnd(MergeBlock->getTerminator());
35327b9f5ca2SSiddharth Bhat       }
35337b9f5ca2SSiddharth Bhat 
353471dfb3ebSSiddharth Bhat       NodeBuilder.addParameters(S->getContext().release());
3535cb1aef8dSTobias Grosser       Value *RTC = NodeBuilder.createRTC(Condition);
3536cb1aef8dSTobias Grosser       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3537cb1aef8dSTobias Grosser 
353838fc0aedSTobias Grosser       Builder.SetInsertPoint(&*StartBlock->begin());
3539fa7b0802STobias Grosser 
354038fc0aedSTobias Grosser       NodeBuilder.create(Root);
354171dfb3ebSSiddharth Bhat     }
35425857b701STobias Grosser 
3543bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3544bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3545de244eb4STobias Grosser     /// point in running it on a GPU.
3546bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
354703346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3548bc653f20STobias Grosser 
35495857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
355003346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
355138fc0aedSTobias Grosser   }
355238fc0aedSTobias Grosser 
3553e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3554e938517eSTobias Grosser     S = &CurrentScop;
355538fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
355638fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
355738fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
35587b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
355938fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3560e938517eSTobias Grosser 
3561349506a9SNicola Zaghen     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3562656e6295SSiddharth Bhat                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3563656e6295SSiddharth Bhat 
3564f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3565f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3566f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3567bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3568bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
35698fc6cdfbSTobias Grosser     if (containsInvalidKernelFunction(CurrentScop,
35708fc6cdfbSTobias Grosser                                       Architecture == GPUArch::NVPTX64)) {
3571349506a9SNicola Zaghen       LLVM_DEBUG(
3572638316daSSiddharth Bhat           dbgs() << getUniqueScopName(S)
3573638316daSSiddharth Bhat                  << " contains function which cannot be materialised in a GPU "
3574f291c8d5SSiddharth Bhat                     "kernel. Bailing out.\n";);
3575bccaea57SSiddharth Bhat       return false;
3576f291c8d5SSiddharth Bhat     }
3577bccaea57SSiddharth Bhat 
3578e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3579e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3580f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
358138fc0aedSTobias Grosser 
358202ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
358332837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
358402ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
3585638316daSSiddharth Bhat     } else {
3586349506a9SNicola Zaghen       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3587638316daSSiddharth Bhat                         << " has empty PPCGGen->tree. Bailing out.\n");
358802ca346eSSingapuram Sanjay Srivallabh     }
358938fc0aedSTobias Grosser 
3590b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3591f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3592e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3593e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3594e938517eSTobias Grosser 
3595e938517eSTobias Grosser     return true;
3596e938517eSTobias Grosser   }
35979dfe4e7cSTobias Grosser 
35989dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
35999dfe4e7cSTobias Grosser 
36009dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
3601a4f447c2SMichael Kruse     ScopPass::getAnalysisUsage(AU);
3602a4f447c2SMichael Kruse 
36039dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
36049dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
36059dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
36065cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
36079dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
36089dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
36099dfe4e7cSTobias Grosser 
36109dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
36119dfe4e7cSTobias Grosser     //        region tree.
36129dfe4e7cSTobias Grosser   }
36139dfe4e7cSTobias Grosser };
361424222c73STobias Grosser } // namespace
36159dfe4e7cSTobias Grosser 
36169dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
36179dfe4e7cSTobias Grosser 
361817f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
361917f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
362017f01968SSiddharth Bhat   generator->Runtime = Runtime;
362117f01968SSiddharth Bhat   generator->Architecture = Arch;
362217f01968SSiddharth Bhat   return generator;
362317f01968SSiddharth Bhat }
36249dfe4e7cSTobias Grosser 
36259dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
36269dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
36279dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
36289dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
36299dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
36309dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
36319dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
36325cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
36339dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
36349dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3635