19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h"
16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h"
179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
21f384594dSTobias Grosser #include "polly/Options.h"
22629109b6STobias Grosser #include "polly/ScopDetection.h"
239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
33e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
399dfe4e7cSTobias Grosser 
40f384594dSTobias Grosser #include "isl/union_map.h"
41f384594dSTobias Grosser 
42e938517eSTobias Grosser extern "C" {
43a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
44a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
47a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
48e938517eSTobias Grosser }
49e938517eSTobias Grosser 
509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
519dfe4e7cSTobias Grosser 
529dfe4e7cSTobias Grosser using namespace polly;
539dfe4e7cSTobias Grosser using namespace llvm;
549dfe4e7cSTobias Grosser 
559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
569dfe4e7cSTobias Grosser 
57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
58f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
59681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
60f384594dSTobias Grosser                                   cl::cat(PollyCategory));
6169b46751STobias Grosser 
6269b46751STobias Grosser static cl::opt<bool>
6369b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6469b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6569b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6669b46751STobias Grosser 
6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6832837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6932837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
7032837fe3STobias Grosser                                   cl::cat(PollyCategory));
7132837fe3STobias Grosser 
7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7374dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7474dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7574dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7674dc3cb4STobias Grosser 
7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7874dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7974dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
8074dc3cb4STobias Grosser                               cl::cat(PollyCategory));
81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
82b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
83b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
84b513b491STobias Grosser                                   cl::cat(PollyCategory));
85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private",
86130ca30fSTobias Grosser                                    cl::desc("Use private memory"), cl::Hidden,
87130ca30fSTobias Grosser                                    cl::init(false), cl::ZeroOrMore,
88130ca30fSTobias Grosser                                    cl::cat(PollyCategory));
8974dc3cb4STobias Grosser 
90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory",
91abed4969SSiddharth Bhat                                    cl::desc("Generate Host kernel code assuming"
92abed4969SSiddharth Bhat                                             " that all memory has been"
93abed4969SSiddharth Bhat                                             " declared as managed memory"),
94abed4969SSiddharth Bhat                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
95abed4969SSiddharth Bhat                                    cl::cat(PollyCategory));
96abed4969SSiddharth Bhat 
9765d7f72fSSiddharth Bhat static cl::opt<bool>
9865d7f72fSSiddharth Bhat     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
9965d7f72fSSiddharth Bhat                               cl::desc("Fail and generate a backtrace if"
10065d7f72fSSiddharth Bhat                                        " verifyModule fails on the GPU "
10165d7f72fSSiddharth Bhat                                        " kernel module."),
10265d7f72fSSiddharth Bhat                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
10365d7f72fSSiddharth Bhat                               cl::cat(PollyCategory));
10465d7f72fSSiddharth Bhat 
10574dc3cb4STobias Grosser static cl::opt<std::string>
10674dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
10774dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
10874dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
10974dc3cb4STobias Grosser 
11082f2af35STobias Grosser static cl::opt<int>
11182f2af35STobias Grosser     MinCompute("polly-acc-mincompute",
11282f2af35STobias Grosser                cl::desc("Minimal number of compute statements to run on GPU."),
11382f2af35STobias Grosser                cl::Hidden, cl::init(10 * 512 * 512));
11482f2af35STobias Grosser 
115a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is
116a82f2d26SSiddharth Bhat /// used by live range reordering.
117a82f2d26SSiddharth Bhat ///
118a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering
119a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop
120a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg
121a82f2d26SSiddharth Bhat struct MustKillsInfo {
122a82f2d26SSiddharth Bhat   /// Collection of all kill statements that will be sequenced at the end of
123a82f2d26SSiddharth Bhat   /// PPCGScop->schedule.
124a82f2d26SSiddharth Bhat   ///
125a82f2d26SSiddharth Bhat   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
126a82f2d26SSiddharth Bhat   /// which merges schedules in *arbitrary* order.
127a82f2d26SSiddharth Bhat   /// (we don't care about the order of the kills anyway).
128a82f2d26SSiddharth Bhat   isl::schedule KillsSchedule;
129a82f2d26SSiddharth Bhat   /// Map from kill statement instances to scalars that need to be
130a82f2d26SSiddharth Bhat   /// killed.
131a82f2d26SSiddharth Bhat   ///
132edfef5aeSSiddharth Bhat   /// We currently derive kill information for:
133edfef5aeSSiddharth Bhat   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
134edfef5aeSSiddharth Bhat   ///     consequently all be killed.
135edfef5aeSSiddharth Bhat   ///  2. Scalar arrays that are not used outside the Scop. This is
136edfef5aeSSiddharth Bhat   ///     checked by `isScalarUsesContainedInScop`.
137edfef5aeSSiddharth Bhat   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
138a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
139a82f2d26SSiddharth Bhat 
140*9e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
141*9e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
142*9e3db2b7SSiddharth Bhat   isl::union_map MustKills;
143*9e3db2b7SSiddharth Bhat 
144*9e3db2b7SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr) {}
145a82f2d26SSiddharth Bhat };
146a82f2d26SSiddharth Bhat 
147761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
148761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
149761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
150761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
151761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
152761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
153761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
154761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
155761e5b93SSiddharth Bhat 
156761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
157761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
158761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
159761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
160761e5b93SSiddharth Bhat     if (!R.contains(I))
161761e5b93SSiddharth Bhat       return false;
162761e5b93SSiddharth Bhat   }
163761e5b93SSiddharth Bhat   return true;
164761e5b93SSiddharth Bhat }
165761e5b93SSiddharth Bhat 
166a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
167a82f2d26SSiddharth Bhat ///
168a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
169a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
170a82f2d26SSiddharth Bhat /// PPCG.
171a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
172a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
173a82f2d26SSiddharth Bhat   MustKillsInfo Info;
174a82f2d26SSiddharth Bhat 
175761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
176761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
177761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
178a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
179a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
180761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
181761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
182a82f2d26SSiddharth Bhat       KillMemIds.push_back(isl::manage(SAI->getBasePtrId()));
183a82f2d26SSiddharth Bhat   }
184a82f2d26SSiddharth Bhat 
185a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
186*9e3db2b7SSiddharth Bhat   Info.MustKills = isl::union_map::empty(isl::space(ParamSpace));
187a82f2d26SSiddharth Bhat 
188a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
189a82f2d26SSiddharth Bhat   // schedule:
190a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
191a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
192a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
193a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
194a82f2d26SSiddharth Bhat 
195edfef5aeSSiddharth Bhat   for (isl::id &ToKillId : KillMemIds) {
196a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
197edfef5aeSSiddharth Bhat         S.getIslCtx(),
198edfef5aeSSiddharth Bhat         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
199a82f2d26SSiddharth Bhat 
200a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
201a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
202edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
203a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
204edfef5aeSSiddharth Bhat     // 2a. StmtToScalar:
205edfef5aeSSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
206edfef5aeSSiddharth Bhat     // 2b. PhantomRefToScalar:
207edfef5aeSSiddharth Bhat     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
208a82f2d26SSiddharth Bhat     //
209a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
210a82f2d26SSiddharth Bhat     // TaggedMustKill:
211edfef5aeSSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
212a82f2d26SSiddharth Bhat 
213edfef5aeSSiddharth Bhat     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
214edfef5aeSSiddharth Bhat     isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace));
215edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
216edfef5aeSSiddharth Bhat     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
217a82f2d26SSiddharth Bhat 
218a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
219edfef5aeSSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
220edfef5aeSSiddharth Bhat         nullptr);
221a82f2d26SSiddharth Bhat 
222edfef5aeSSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
223edfef5aeSSiddharth Bhat     isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace));
224edfef5aeSSiddharth Bhat     PhantomRefToScalar =
225edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
226edfef5aeSSiddharth Bhat     PhantomRefToScalar =
227edfef5aeSSiddharth Bhat         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
228a82f2d26SSiddharth Bhat 
229edfef5aeSSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
230edfef5aeSSiddharth Bhat     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
231a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
232a82f2d26SSiddharth Bhat 
233*9e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
234*9e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
235*9e3db2b7SSiddharth Bhat 
236a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
237a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
238a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
239a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
240a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
241a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
242a82f2d26SSiddharth Bhat 
243a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
244a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
245a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
246a82f2d26SSiddharth Bhat     else
247a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
248a82f2d26SSiddharth Bhat   }
249a82f2d26SSiddharth Bhat 
250a82f2d26SSiddharth Bhat   return Info;
251a82f2d26SSiddharth Bhat }
252a82f2d26SSiddharth Bhat 
25360c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
25460c60025STobias Grosser ///
25560c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
25660c60025STobias Grosser /// of the scheduled ScopStmts.
25760c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
258edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
25960c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
26060c60025STobias Grosser                                        isl_id *Id, void *User),
26160c60025STobias Grosser     void *UserIndex,
26260c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
263edb885cbSTobias Grosser     void *UserExpr) {
26460c60025STobias Grosser 
265edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
26660c60025STobias Grosser 
267edb885cbSTobias Grosser   isl_ctx *Ctx;
268edb885cbSTobias Grosser 
269edb885cbSTobias Grosser   if (!Stmt || !Build)
270edb885cbSTobias Grosser     return NULL;
271edb885cbSTobias Grosser 
272edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
273edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
274edb885cbSTobias Grosser 
275edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
276edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
277edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
278edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
279edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
280edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
281edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
282edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
283edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
284edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
285edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
286edb885cbSTobias Grosser   }
287edb885cbSTobias Grosser 
288edb885cbSTobias Grosser   return RefToExpr;
28960c60025STobias Grosser }
290f384594dSTobias Grosser 
291a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
292a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
293a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
294a90be207SSiddharth Bhat   if (bytes == 0)
295a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
296a90be207SSiddharth Bhat   return bytes;
297a90be207SSiddharth Bhat }
298a90be207SSiddharth Bhat 
29938fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
30038fc0aedSTobias Grosser ///
30138fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
302a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
30338fc0aedSTobias Grosser /// for generating GPU specific user nodes.
30438fc0aedSTobias Grosser ///
30538fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
30638fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
30738fc0aedSTobias Grosser public:
3082d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
30938fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
310acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
31117f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3122d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
31317f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
314edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
315edb885cbSTobias Grosser   }
31638fc0aedSTobias Grosser 
317fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
318fa7b0802STobias Grosser   void initializeAfterRTH();
319fa7b0802STobias Grosser 
320fa7b0802STobias Grosser   /// Finalize the generated scop.
321fa7b0802STobias Grosser   virtual void finalize();
322fa7b0802STobias Grosser 
3235857b701STobias Grosser   /// Track if the full build process was successful.
3245857b701STobias Grosser   ///
3255857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3265857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3275857b701STobias Grosser   bool BuildSuccessful = true;
3285857b701STobias Grosser 
329bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
330bc653f20STobias Grosser   unsigned DeepestSequential = 0;
331bc653f20STobias Grosser 
332bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
333bc653f20STobias Grosser   unsigned DeepestParallel = 0;
334bc653f20STobias Grosser 
33579f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
33679f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
33779f13b9aSSingapuram Sanjay Srivallabh 
33838fc0aedSTobias Grosser private:
33974dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
34074dc3cb4STobias Grosser   ///
34174dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
34274dc3cb4STobias Grosser   /// more.
34374dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
34474dc3cb4STobias Grosser 
34513c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
34613c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3477287aeddSTobias Grosser 
348fa7b0802STobias Grosser   /// The current GPU context.
349fa7b0802STobias Grosser   Value *GPUContext;
350fa7b0802STobias Grosser 
351b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
352b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
353b513b491STobias Grosser 
35432837fe3STobias Grosser   /// A module containing GPU code.
35532837fe3STobias Grosser   ///
35632837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
35732837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
35832837fe3STobias Grosser 
35932837fe3STobias Grosser   /// The GPU program we generate code for.
36032837fe3STobias Grosser   gpu_prog *Prog;
36132837fe3STobias Grosser 
36217f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
36317f01968SSiddharth Bhat   GPURuntime Runtime;
36417f01968SSiddharth Bhat 
36517f01968SSiddharth Bhat   /// The GPU Architecture to target.
36617f01968SSiddharth Bhat   GPUArch Arch;
36717f01968SSiddharth Bhat 
368472f9654STobias Grosser   /// Class to free isl_ids.
369472f9654STobias Grosser   class IslIdDeleter {
370472f9654STobias Grosser   public:
371472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
372472f9654STobias Grosser   };
373472f9654STobias Grosser 
374472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
375472f9654STobias Grosser   ///
376472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
377472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
378472f9654STobias Grosser 
379edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
380edb885cbSTobias Grosser 
38138fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
38238fc0aedSTobias Grosser   ///
38338fc0aedSTobias Grosser   /// These AST nodes can be of type:
38438fc0aedSTobias Grosser   ///
38538fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
38638fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
38713c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
3885260c041STobias Grosser   ///   - In-kernel synchronization
3895260c041STobias Grosser   ///   - In-kernel memory copy statement
39038fc0aedSTobias Grosser   ///
3911fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
3921fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
39332837fe3STobias Grosser 
39413c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
39513c78e4dSTobias Grosser 
39613c78e4dSTobias Grosser   /// Create code for a data transfer statement
39713c78e4dSTobias Grosser   ///
39813c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
39913c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
40013c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
40113c78e4dSTobias Grosser                           enum DataDirection Direction);
40213c78e4dSTobias Grosser 
403edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
404edb885cbSTobias Grosser   ///
405edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
406edb885cbSTobias Grosser   ///
407f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
408f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
409f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
410f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
411f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
412f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
413edb885cbSTobias Grosser 
41479a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
41579a947c2STobias Grosser   ///
41679a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
41779a947c2STobias Grosser   ///
41879a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
41979a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
42079a947c2STobias Grosser 
421abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
422abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
423abed4969SSiddharth Bhat   /// host pointers to the device.
424abed4969SSiddharth Bhat   /// \note
425abed4969SSiddharth Bhat   /// This is to be used only with managed memory
426abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
427abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
428abed4969SSiddharth Bhat 
42979a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
43079a947c2STobias Grosser   ///
43179a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
43279a947c2STobias Grosser   ///
43379a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
43479a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
43579a947c2STobias Grosser 
436a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
437a90be207SSiddharth Bhat   /// parameters.
438a90be207SSiddharth Bhat   ///
439a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
440a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
441a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
442a90be207SSiddharth Bhat   ///                   parameter.
443a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
444a90be207SSiddharth Bhat                             int Index);
445a90be207SSiddharth Bhat 
44679a947c2STobias Grosser   /// Create kernel launch parameters.
44779a947c2STobias Grosser   ///
44879a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
44979a947c2STobias Grosser   /// @param F             The kernel function that has been created.
45057693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
45179a947c2STobias Grosser   ///
45279a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
45379a947c2STobias Grosser   ///          values that are passed to the kernel.
45457693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
45557693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
45679a947c2STobias Grosser 
457b513b491STobias Grosser   /// Create declarations for kernel variable.
458b513b491STobias Grosser   ///
459b513b491STobias Grosser   /// This includes shared memory declarations.
460b513b491STobias Grosser   ///
461b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
462b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
463b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
464b513b491STobias Grosser 
465c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
466c1c6a2a6STobias Grosser   ///
467c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
468c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
469c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
470c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
471c1c6a2a6STobias Grosser   /// as specified here.
472c1c6a2a6STobias Grosser   ///
473c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
474c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
475c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
476c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
477c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
478c1c6a2a6STobias Grosser                           Value *BlockDimZ);
479c1c6a2a6STobias Grosser 
48032837fe3STobias Grosser   /// Create GPU kernel.
48132837fe3STobias Grosser   ///
48232837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
48332837fe3STobias Grosser   ///
48432837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
48532837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
48632837fe3STobias Grosser 
48713c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
48813c78e4dSTobias Grosser   ///
48913c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
49013c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
49113c78e4dSTobias Grosser 
492aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
493aaabbbf8STobias Grosser   ///
494aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
495aaabbbf8STobias Grosser   ///
496aaabbbf8STobias Grosser   /// Example:
497aaabbbf8STobias Grosser   ///
498aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
499aaabbbf8STobias Grosser   ///     A[i + 42] += ...
500aaabbbf8STobias Grosser   ///
501aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
502aaabbbf8STobias Grosser   ///
503aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
504aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
505aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
506aaabbbf8STobias Grosser 
50700bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
50800bb5a99STobias Grosser   ///
50900bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
51000bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
51100bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
51200bb5a99STobias Grosser 
51332837fe3STobias Grosser   /// Create kernel function.
51432837fe3STobias Grosser   ///
51532837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
51632837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
51732837fe3STobias Grosser   /// start block of this newly created function.
51832837fe3STobias Grosser   ///
51932837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
520edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
521f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
522f291c8d5SSiddharth Bhat   ///                         kernel.
523edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
524f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
525f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
52632837fe3STobias Grosser 
52732837fe3STobias Grosser   /// Create the declaration of a kernel function.
52832837fe3STobias Grosser   ///
52932837fe3STobias Grosser   /// The kernel function takes as arguments:
53032837fe3STobias Grosser   ///
53132837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
532f6044bd0STobias Grosser   ///   - Host iterators
533c84a1995STobias Grosser   ///   - Parameters
53432837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
53532837fe3STobias Grosser   ///
53632837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
537edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
538edb885cbSTobias Grosser   ///
53932837fe3STobias Grosser   /// @returns The newly declared function.
540edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
541edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
54232837fe3STobias Grosser 
543472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
544472f9654STobias Grosser   ///
545472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
546472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
547472f9654STobias Grosser 
548f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
549f291c8d5SSiddharth Bhat   ///
550f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
551f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
552f291c8d5SSiddharth Bhat   ///
553f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
554f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
555f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
556f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
557f291c8d5SSiddharth Bhat   ///
558f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
559f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
560f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
561f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
562f291c8d5SSiddharth Bhat   ///
563f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
564f291c8d5SSiddharth Bhat   ///                         this kernel.
565f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
566f291c8d5SSiddharth Bhat 
567b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
568b513b491STobias Grosser   ///
569b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
570b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
571b513b491STobias Grosser 
572edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
573edb885cbSTobias Grosser   ///
574edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
575edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
576edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
577edb885cbSTobias Grosser 
5785260c041STobias Grosser   /// Create an in-kernel synchronization call.
5795260c041STobias Grosser   void createKernelSync();
5805260c041STobias Grosser 
58174dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
58274dc3cb4STobias Grosser   ///
58374dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
58474dc3cb4STobias Grosser   std::string createKernelASM();
58574dc3cb4STobias Grosser 
58674dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
58774dc3cb4STobias Grosser   ///
58874dc3cb4STobias Grosser   /// @param F The function to remove references to.
58974dc3cb4STobias Grosser   void clearDominators(Function *F);
59074dc3cb4STobias Grosser 
59174dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
59274dc3cb4STobias Grosser   ///
59374dc3cb4STobias Grosser   /// @param F The function to remove references to.
59474dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
59574dc3cb4STobias Grosser 
59674dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
59774dc3cb4STobias Grosser   ///
59874dc3cb4STobias Grosser   /// @param F The function to remove references to.
59974dc3cb4STobias Grosser   void clearLoops(Function *F);
60074dc3cb4STobias Grosser 
60132837fe3STobias Grosser   /// Finalize the generation of the kernel function.
60232837fe3STobias Grosser   ///
60332837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
60432837fe3STobias Grosser   /// dump its IR to stderr.
60557793596STobias Grosser   ///
60657793596STobias Grosser   /// @returns The Assembly string of the kernel.
60757793596STobias Grosser   std::string finalizeKernelFunction();
608fa7b0802STobias Grosser 
60951dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
61051dfc275STobias Grosser   ///
61151dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
612a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
61351dfc275STobias Grosser   /// the kernel terminates.
61451dfc275STobias Grosser   ///
61551dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
61651dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
61751dfc275STobias Grosser 
6187287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
619fa7b0802STobias Grosser   void allocateDeviceArrays();
620fa7b0802STobias Grosser 
6217287aeddSTobias Grosser   /// Free all allocated device arrays.
6227287aeddSTobias Grosser   void freeDeviceArrays();
6237287aeddSTobias Grosser 
624fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
625fa7b0802STobias Grosser   ///
626fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
627fa7b0802STobias Grosser   Value *createCallInitContext();
628fa7b0802STobias Grosser 
62979a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
63079a947c2STobias Grosser   ///
63179a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
63279a947c2STobias Grosser   ///
63379a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
63479a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
63579a947c2STobias Grosser 
636fa7b0802STobias Grosser   /// Create a call to free the GPU context.
637fa7b0802STobias Grosser   ///
638fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
639fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
640fa7b0802STobias Grosser 
6417287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6427287aeddSTobias Grosser   ///
6437287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6447287aeddSTobias Grosser   ///
6457287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
646fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6477287aeddSTobias Grosser 
6487287aeddSTobias Grosser   /// Create a call to free a device array.
6497287aeddSTobias Grosser   ///
6507287aeddSTobias Grosser   /// @param Array The device array to free.
6517287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
65213c78e4dSTobias Grosser 
65313c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
65413c78e4dSTobias Grosser   ///
65513c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
65613c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
65713c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
65813c78e4dSTobias Grosser                                       Value *Size);
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
66113c78e4dSTobias Grosser   ///
66213c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
66313c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
66413c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
66513c78e4dSTobias Grosser                                       Value *Size);
66657793596STobias Grosser 
667abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
668abed4969SSiddharth Bhat   /// \note
669abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
670abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
671abed4969SSiddharth Bhat 
67257793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
67357793596STobias Grosser   ///
67457793596STobias Grosser   /// @param Buffer The string describing the kernel.
67557793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
67657793596STobias Grosser   ///
67757793596STobias Grosser   /// @returns A pointer to a kernel object
67857793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
67957793596STobias Grosser 
68057793596STobias Grosser   /// Create a call to free a GPU kernel.
68157793596STobias Grosser   ///
68257793596STobias Grosser   /// @param GPUKernel THe kernel to free.
68357793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
68479a947c2STobias Grosser 
68579a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
68679a947c2STobias Grosser   ///
68779a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
68879a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
68979a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
69079a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
69179a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
69279a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
693a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
69479a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
69579a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
69679a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
69779a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
69879a947c2STobias Grosser                               Value *Parameters);
6991fb9b64dSTobias Grosser };
7001fb9b64dSTobias Grosser 
70179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7021abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7031abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
70479f13b9aSSingapuram Sanjay Srivallabh }
70579f13b9aSSingapuram Sanjay Srivallabh 
706fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
707750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
708750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
709750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
710750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
711750160e2STobias Grosser 
712fa7b0802STobias Grosser   GPUContext = createCallInitContext();
713abed4969SSiddharth Bhat 
714abed4969SSiddharth Bhat   if (!ManagedMemory)
715fa7b0802STobias Grosser     allocateDeviceArrays();
716fa7b0802STobias Grosser }
717fa7b0802STobias Grosser 
718fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
719abed4969SSiddharth Bhat   if (!ManagedMemory)
7207287aeddSTobias Grosser     freeDeviceArrays();
721abed4969SSiddharth Bhat 
722fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
723fa7b0802STobias Grosser   IslNodeBuilder::finalize();
724fa7b0802STobias Grosser }
725fa7b0802STobias Grosser 
726fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
727abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
728abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
729fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
730fa7b0802STobias Grosser 
731fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
732fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
73313c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7347287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7357287aeddSTobias Grosser     DevArrayName.append(Array->name);
736fa7b0802STobias Grosser 
73713c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
738aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
739aaabbbf8STobias Grosser     if (Offset)
740aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
741aaabbbf8STobias Grosser           ArraySize,
742aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
743aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7447287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7457287aeddSTobias Grosser     DevArray->setName(DevArrayName);
74613c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
747fa7b0802STobias Grosser   }
748fa7b0802STobias Grosser 
749fa7b0802STobias Grosser   isl_ast_build_free(Build);
750fa7b0802STobias Grosser }
751fa7b0802STobias Grosser 
752c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
753c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
754c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
755c1c6a2a6STobias Grosser 
756c1c6a2a6STobias Grosser   for (auto &F : *M) {
757c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
758c1c6a2a6STobias Grosser       continue;
759c1c6a2a6STobias Grosser 
760c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
761c1c6a2a6STobias Grosser 
762c1c6a2a6STobias Grosser     Metadata *Elements[] = {
763c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
764c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
765c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
766c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
767c1c6a2a6STobias Grosser     };
768c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
769c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
770c1c6a2a6STobias Grosser   }
771c1c6a2a6STobias Grosser }
772c1c6a2a6STobias Grosser 
7737287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
774abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
77513c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
77613c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
7777287aeddSTobias Grosser }
7787287aeddSTobias Grosser 
77957793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
78057793596STobias Grosser   const char *Name = "polly_getKernel";
78157793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
78257793596STobias Grosser   Function *F = M->getFunction(Name);
78357793596STobias Grosser 
78457793596STobias Grosser   // If F is not available, declare it.
78557793596STobias Grosser   if (!F) {
78657793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
78757793596STobias Grosser     std::vector<Type *> Args;
78857793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
78957793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
79057793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
79157793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
79257793596STobias Grosser   }
79357793596STobias Grosser 
79457793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
79557793596STobias Grosser }
79657793596STobias Grosser 
79779a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
79879a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
79979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
80079a947c2STobias Grosser   Function *F = M->getFunction(Name);
80179a947c2STobias Grosser 
80279a947c2STobias Grosser   // If F is not available, declare it.
80379a947c2STobias Grosser   if (!F) {
80479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
80579a947c2STobias Grosser     std::vector<Type *> Args;
80679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
80779a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
80879a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
80979a947c2STobias Grosser   }
81079a947c2STobias Grosser 
81179a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
81279a947c2STobias Grosser }
81379a947c2STobias Grosser 
81479a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
81579a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
81679a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
81779a947c2STobias Grosser                                             Value *Parameters) {
81879a947c2STobias Grosser   const char *Name = "polly_launchKernel";
81979a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
82079a947c2STobias Grosser   Function *F = M->getFunction(Name);
82179a947c2STobias Grosser 
82279a947c2STobias Grosser   // If F is not available, declare it.
82379a947c2STobias Grosser   if (!F) {
82479a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
82579a947c2STobias Grosser     std::vector<Type *> Args;
82679a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
82879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
82979a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83279a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
83379a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
83479a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
83579a947c2STobias Grosser   }
83679a947c2STobias Grosser 
837ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
83879a947c2STobias Grosser                          BlockDimZ, Parameters});
83979a947c2STobias Grosser }
84079a947c2STobias Grosser 
84157793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
84257793596STobias Grosser   const char *Name = "polly_freeKernel";
84357793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
84457793596STobias Grosser   Function *F = M->getFunction(Name);
84557793596STobias Grosser 
84657793596STobias Grosser   // If F is not available, declare it.
84757793596STobias Grosser   if (!F) {
84857793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
84957793596STobias Grosser     std::vector<Type *> Args;
85057793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85157793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
85257793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
85357793596STobias Grosser   }
85457793596STobias Grosser 
85557793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
85657793596STobias Grosser }
85757793596STobias Grosser 
8587287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
859abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
860abed4969SSiddharth Bhat                            "for device");
8617287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8627287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8637287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8647287aeddSTobias Grosser 
8657287aeddSTobias Grosser   // If F is not available, declare it.
8667287aeddSTobias Grosser   if (!F) {
8677287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8687287aeddSTobias Grosser     std::vector<Type *> Args;
8697287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8707287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8717287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8727287aeddSTobias Grosser   }
8737287aeddSTobias Grosser 
8747287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
8757287aeddSTobias Grosser }
8767287aeddSTobias Grosser 
877fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
878abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
879abed4969SSiddharth Bhat                            "for device");
880fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
881fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
882fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
883fa7b0802STobias Grosser 
884fa7b0802STobias Grosser   // If F is not available, declare it.
885fa7b0802STobias Grosser   if (!F) {
886fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
887fa7b0802STobias Grosser     std::vector<Type *> Args;
888fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
889fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
890fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
891fa7b0802STobias Grosser   }
892fa7b0802STobias Grosser 
893fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
894fa7b0802STobias Grosser }
895fa7b0802STobias Grosser 
89613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
89713c78e4dSTobias Grosser                                                     Value *DeviceData,
89813c78e4dSTobias Grosser                                                     Value *Size) {
899abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
900abed4969SSiddharth Bhat                            "device and host");
90113c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
90213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
90413c78e4dSTobias Grosser 
90513c78e4dSTobias Grosser   // If F is not available, declare it.
90613c78e4dSTobias Grosser   if (!F) {
90713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
90813c78e4dSTobias Grosser     std::vector<Type *> Args;
90913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
91213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
91313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
91413c78e4dSTobias Grosser   }
91513c78e4dSTobias Grosser 
91613c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
91713c78e4dSTobias Grosser }
91813c78e4dSTobias Grosser 
91913c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
92013c78e4dSTobias Grosser                                                     Value *HostData,
92113c78e4dSTobias Grosser                                                     Value *Size) {
922abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
923abed4969SSiddharth Bhat                            "device and host");
92413c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
92513c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92613c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
92713c78e4dSTobias Grosser 
92813c78e4dSTobias Grosser   // If F is not available, declare it.
92913c78e4dSTobias Grosser   if (!F) {
93013c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93113c78e4dSTobias Grosser     std::vector<Type *> Args;
93213c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93313c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
93413c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
93513c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
93613c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
93713c78e4dSTobias Grosser   }
93813c78e4dSTobias Grosser 
93913c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
94013c78e4dSTobias Grosser }
94113c78e4dSTobias Grosser 
942abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
943abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
944abed4969SSiddharth Bhat                           "managed memory");
945abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
946abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
947abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
948abed4969SSiddharth Bhat 
949abed4969SSiddharth Bhat   // If F is not available, declare it.
950abed4969SSiddharth Bhat   if (!F) {
951abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
952abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
953abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
954abed4969SSiddharth Bhat   }
955abed4969SSiddharth Bhat 
956abed4969SSiddharth Bhat   Builder.CreateCall(F);
957abed4969SSiddharth Bhat }
958abed4969SSiddharth Bhat 
959fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
96017f01968SSiddharth Bhat   const char *Name;
96117f01968SSiddharth Bhat 
96217f01968SSiddharth Bhat   switch (Runtime) {
96317f01968SSiddharth Bhat   case GPURuntime::CUDA:
96417f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
96517f01968SSiddharth Bhat     break;
96617f01968SSiddharth Bhat   case GPURuntime::OpenCL:
96717f01968SSiddharth Bhat     Name = "polly_initContextCL";
96817f01968SSiddharth Bhat     break;
96917f01968SSiddharth Bhat   }
97017f01968SSiddharth Bhat 
971fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
972fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
973fa7b0802STobias Grosser 
974fa7b0802STobias Grosser   // If F is not available, declare it.
975fa7b0802STobias Grosser   if (!F) {
976fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
977fa7b0802STobias Grosser     std::vector<Type *> Args;
978fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
979fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
980fa7b0802STobias Grosser   }
981fa7b0802STobias Grosser 
982fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
983fa7b0802STobias Grosser }
984fa7b0802STobias Grosser 
985fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
986fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
987fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
988fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
989fa7b0802STobias Grosser 
990fa7b0802STobias Grosser   // If F is not available, declare it.
991fa7b0802STobias Grosser   if (!F) {
992fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
993fa7b0802STobias Grosser     std::vector<Type *> Args;
994fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
995fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
996fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
997fa7b0802STobias Grosser   }
998fa7b0802STobias Grosser 
999fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1000fa7b0802STobias Grosser }
1001fa7b0802STobias Grosser 
10025260c041STobias Grosser /// Check if one string is a prefix of another.
10035260c041STobias Grosser ///
10045260c041STobias Grosser /// @param String The string in which to look for the prefix.
10055260c041STobias Grosser /// @param Prefix The prefix to look for.
10065260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10075260c041STobias Grosser   return String.find(Prefix) == 0;
10085260c041STobias Grosser }
10095260c041STobias Grosser 
101013c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
101113c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
101213c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
101313c78e4dSTobias Grosser 
101413c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1015*9e3db2b7SSiddharth Bhat     auto OffsetDimZero = isl_multi_pw_aff_get_pw_aff(Array->bound, 0);
101613c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
101713c78e4dSTobias Grosser 
101813c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1019*9e3db2b7SSiddharth Bhat       isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i);
102013c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
102113c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
102213c78e4dSTobias Grosser     }
102313c78e4dSTobias Grosser 
102413c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
1025b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1026b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
102713c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
102813c78e4dSTobias Grosser   }
102913c78e4dSTobias Grosser   isl_ast_build_free(Build);
103013c78e4dSTobias Grosser   return ArraySize;
103113c78e4dSTobias Grosser }
103213c78e4dSTobias Grosser 
1033aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1034aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1035aaabbbf8STobias Grosser     return nullptr;
1036aaabbbf8STobias Grosser 
1037aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
1038aaabbbf8STobias Grosser 
1039aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
1040aaabbbf8STobias Grosser 
1041aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
1042aaabbbf8STobias Grosser 
1043aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
1044aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
1045aaabbbf8STobias Grosser 
1046aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
1047aaabbbf8STobias Grosser     isl_set_free(Min);
1048aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
1049aaabbbf8STobias Grosser     isl_ast_build_free(Build);
1050aaabbbf8STobias Grosser     return nullptr;
1051aaabbbf8STobias Grosser   }
1052aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
1053aaabbbf8STobias Grosser 
1054aaabbbf8STobias Grosser   isl_ast_expr *Result =
1055aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
1056aaabbbf8STobias Grosser 
1057aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
1058aaabbbf8STobias Grosser     if (i > 0) {
1059*9e3db2b7SSiddharth Bhat       isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1);
1060aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
1061aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
1062aaabbbf8STobias Grosser     }
1063aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
1064aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
1065aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
1066aaabbbf8STobias Grosser   }
1067aaabbbf8STobias Grosser 
1068aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
1069aaabbbf8STobias Grosser   isl_set_free(Min);
1070aaabbbf8STobias Grosser   isl_ast_build_free(Build);
1071aaabbbf8STobias Grosser 
1072aaabbbf8STobias Grosser   return ResultValue;
1073aaabbbf8STobias Grosser }
1074aaabbbf8STobias Grosser 
1075abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1076abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1077abed4969SSiddharth Bhat 
1078abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1079abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1080abed4969SSiddharth Bhat                           "with managed memory");
1081abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1082abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1083abed4969SSiddharth Bhat     return it->second;
1084abed4969SSiddharth Bhat   } else {
1085abed4969SSiddharth Bhat     Value *HostPtr;
1086abed4969SSiddharth Bhat 
1087abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1088abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1089abed4969SSiddharth Bhat     else
1090abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1091abed4969SSiddharth Bhat 
1092abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1093abed4969SSiddharth Bhat     if (Offset) {
1094abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1095abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1096abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1097abed4969SSiddharth Bhat     }
1098abed4969SSiddharth Bhat 
1099abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1100abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1101abed4969SSiddharth Bhat     return HostPtr;
1102abed4969SSiddharth Bhat   }
1103abed4969SSiddharth Bhat }
1104abed4969SSiddharth Bhat 
110513c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
110613c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1107abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
110813c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
110913c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
111013c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
111113c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
111213c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
111313c78e4dSTobias Grosser 
111413c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1115aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
111613c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
111713c78e4dSTobias Grosser 
1118b06ff457STobias Grosser   Value *HostPtr;
1119b06ff457STobias Grosser 
1120b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1121b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1122b06ff457STobias Grosser   else
1123b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
112413c78e4dSTobias Grosser 
1125aaabbbf8STobias Grosser   if (Offset) {
1126aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1127aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1128aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1129aaabbbf8STobias Grosser   }
1130aaabbbf8STobias Grosser 
113113c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
113213c78e4dSTobias Grosser 
1133aaabbbf8STobias Grosser   if (Offset) {
1134aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1135ff40087aSTobias Grosser         Size, Builder.CreateMul(
1136ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1137aaabbbf8STobias Grosser   }
1138aaabbbf8STobias Grosser 
113913c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
114013c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
114113c78e4dSTobias Grosser   else
114213c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
114313c78e4dSTobias Grosser 
114413c78e4dSTobias Grosser   isl_id_free(Id);
114513c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
114613c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
114713c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
114813c78e4dSTobias Grosser }
114913c78e4dSTobias Grosser 
11501fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
115132837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
115232837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
115332837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
115432837fe3STobias Grosser   isl_id_free(Id);
115532837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
115632837fe3STobias Grosser 
115732837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
115832837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
115932837fe3STobias Grosser     createKernel(UserStmt);
116032837fe3STobias Grosser     isl_ast_expr_free(Expr);
116132837fe3STobias Grosser     return;
116232837fe3STobias Grosser   }
1163*9e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
1164*9e3db2b7SSiddharth Bhat     initializeAfterRTH();
1165*9e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
1166*9e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
1167*9e3db2b7SSiddharth Bhat     return;
1168*9e3db2b7SSiddharth Bhat   }
1169*9e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
1170*9e3db2b7SSiddharth Bhat     finalize();
1171*9e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
1172*9e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
1173*9e3db2b7SSiddharth Bhat     return;
1174*9e3db2b7SSiddharth Bhat   }
117513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1176abed4969SSiddharth Bhat     if (!ManagedMemory)
117713c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1178abed4969SSiddharth Bhat     else
1179abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1180abed4969SSiddharth Bhat 
118132837fe3STobias Grosser     isl_ast_expr_free(Expr);
118213c78e4dSTobias Grosser     return;
118313c78e4dSTobias Grosser   }
118413c78e4dSTobias Grosser 
118513c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1186abed4969SSiddharth Bhat     if (!ManagedMemory) {
118713c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1188abed4969SSiddharth Bhat     } else {
1189abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1190abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1191abed4969SSiddharth Bhat     }
119213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
119338fc0aedSTobias Grosser     return;
119438fc0aedSTobias Grosser   }
119538fc0aedSTobias Grosser 
11965260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
11975260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
11985260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
11995260c041STobias Grosser   isl_id_free(Anno);
12005260c041STobias Grosser 
12015260c041STobias Grosser   switch (KernelStmt->type) {
12025260c041STobias Grosser   case ppcg_kernel_domain:
1203edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12045260c041STobias Grosser     isl_ast_node_free(UserStmt);
12055260c041STobias Grosser     return;
12065260c041STobias Grosser   case ppcg_kernel_copy:
1207b513b491STobias Grosser     createKernelCopy(KernelStmt);
12085260c041STobias Grosser     isl_ast_expr_free(Expr);
12095260c041STobias Grosser     isl_ast_node_free(UserStmt);
12105260c041STobias Grosser     return;
12115260c041STobias Grosser   case ppcg_kernel_sync:
12125260c041STobias Grosser     createKernelSync();
12135260c041STobias Grosser     isl_ast_expr_free(Expr);
12145260c041STobias Grosser     isl_ast_node_free(UserStmt);
12155260c041STobias Grosser     return;
12165260c041STobias Grosser   }
12175260c041STobias Grosser 
12185260c041STobias Grosser   isl_ast_expr_free(Expr);
12195260c041STobias Grosser   isl_ast_node_free(UserStmt);
12205260c041STobias Grosser   return;
12215260c041STobias Grosser }
1222b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1223b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1224b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1225b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1226b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1227b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1228b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1229b513b491STobias Grosser 
1230b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1231b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1232b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1233b513b491STobias Grosser   } else {
1234b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1235b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1236b513b491STobias Grosser   }
1237b513b491STobias Grosser }
12385260c041STobias Grosser 
1239edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1240edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1241edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1242edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1243edb885cbSTobias Grosser 
1244edb885cbSTobias Grosser   LoopToScevMapT LTS;
1245edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1246edb885cbSTobias Grosser 
1247edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1248edb885cbSTobias Grosser 
1249edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1250edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1251edb885cbSTobias Grosser   else
1252a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1253edb885cbSTobias Grosser }
1254edb885cbSTobias Grosser 
12555260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12565260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
125717f01968SSiddharth Bhat 
125817f01968SSiddharth Bhat   Function *Sync;
125917f01968SSiddharth Bhat 
126017f01968SSiddharth Bhat   switch (Arch) {
126117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
126217f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
126317f01968SSiddharth Bhat     break;
126417f01968SSiddharth Bhat   }
126517f01968SSiddharth Bhat 
12665260c041STobias Grosser   Builder.CreateCall(Sync, {});
12675260c041STobias Grosser }
12685260c041STobias Grosser 
1269edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1270edb885cbSTobias Grosser ///
1271edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1272edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1273edb885cbSTobias Grosser ///
1274edb885cbSTobias Grosser /// @param Node The node to collect references for.
1275edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1276edb885cbSTobias Grosser ///
1277edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1278edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1279edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1280edb885cbSTobias Grosser     return isl_bool_true;
1281edb885cbSTobias Grosser 
1282edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1283edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1284edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1285edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1286edb885cbSTobias Grosser   isl_id_free(Id);
1287edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1288edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1289edb885cbSTobias Grosser 
1290edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1291edb885cbSTobias Grosser     return isl_bool_true;
1292edb885cbSTobias Grosser 
1293edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1294edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1295edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1296edb885cbSTobias Grosser   isl_id_free(Id);
1297edb885cbSTobias Grosser 
129800bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1299edb885cbSTobias Grosser 
1300edb885cbSTobias Grosser   return isl_bool_true;
1301edb885cbSTobias Grosser }
1302edb885cbSTobias Grosser 
1303f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
1304f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) {
1305f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1306f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
1307f291c8d5SSiddharth Bhat   // all variants of the intrinsic "llvm.sqrt.*"
1308f291c8d5SSiddharth Bhat   return F->isIntrinsic() && F->getName().startswith("llvm.sqrt");
1309f291c8d5SSiddharth Bhat }
1310f291c8d5SSiddharth Bhat 
1311f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1312f291c8d5SSiddharth Bhat ///
1313f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1314f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1315f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1316f291c8d5SSiddharth Bhat /// `Function`s.
1317f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1318f291c8d5SSiddharth Bhat 
1319f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1320f291c8d5SSiddharth Bhat static SetVector<Function *>
1321f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1322f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1323f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1324f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1325f291c8d5SSiddharth Bhat     if (F) {
1326f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1327f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1328f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1329f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1330f291c8d5SSiddharth Bhat     }
1331f291c8d5SSiddharth Bhat   }
1332f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1333f291c8d5SSiddharth Bhat }
1334f291c8d5SSiddharth Bhat 
1335f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1336f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1337edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1338edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1339edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1340edb885cbSTobias Grosser   SubtreeReferences References = {
1341edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1342edb885cbSTobias Grosser 
1343edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1344edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1345edb885cbSTobias Grosser 
1346edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1347edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1348edb885cbSTobias Grosser 
1349edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1350edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1351edb885cbSTobias Grosser 
1352edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1353d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1354edb885cbSTobias Grosser 
1355edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1356edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1357edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1358edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1359edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1360edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1361edb885cbSTobias Grosser     isl_id_free(Id);
1362edb885cbSTobias Grosser   }
1363edb885cbSTobias Grosser   isl_space_free(Space);
1364edb885cbSTobias Grosser 
1365edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1366edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1367edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1368edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1369edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1370edb885cbSTobias Grosser     isl_id_free(Id);
1371edb885cbSTobias Grosser   }
1372edb885cbSTobias Grosser 
1373f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1374f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1375f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1376f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1377f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1378f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1379f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1380f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1381f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1382f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1383f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1384f291c8d5SSiddharth Bhat 
1385a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1386a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1387a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1388a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1389a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1390a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1391a1b2086aSSiddharth Bhat     else
1392a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1393a1b2086aSSiddharth Bhat   }
1394a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1395edb885cbSTobias Grosser }
1396edb885cbSTobias Grosser 
139774dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
139874dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
139974dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
140074dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
140174dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
140274dc3cb4STobias Grosser 
140374dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
140474dc3cb4STobias Grosser     DT.eraseNode(BB);
140574dc3cb4STobias Grosser }
140674dc3cb4STobias Grosser 
140774dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
140874dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
140974dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
141074dc3cb4STobias Grosser     if (L)
141174dc3cb4STobias Grosser       SE.forgetLoop(L);
141274dc3cb4STobias Grosser   }
141374dc3cb4STobias Grosser }
141474dc3cb4STobias Grosser 
141574dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
141674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
141774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
141874dc3cb4STobias Grosser     if (L)
141974dc3cb4STobias Grosser       SE.forgetLoop(L);
142074dc3cb4STobias Grosser     LI.removeBlock(&BB);
142174dc3cb4STobias Grosser   }
142274dc3cb4STobias Grosser }
142374dc3cb4STobias Grosser 
142479a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
142579a947c2STobias Grosser   std::vector<Value *> Sizes;
142679a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
142779a947c2STobias Grosser 
142879a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
142979a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
143079a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
143179a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
143279a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
143379a947c2STobias Grosser     Sizes.push_back(Res);
143479a947c2STobias Grosser   }
143579a947c2STobias Grosser   isl_ast_build_free(Context);
143679a947c2STobias Grosser 
143779a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
143879a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
143979a947c2STobias Grosser 
144079a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
144179a947c2STobias Grosser }
144279a947c2STobias Grosser 
144379a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
144479a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
144579a947c2STobias Grosser   std::vector<Value *> Sizes;
144679a947c2STobias Grosser 
144779a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
144879a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
144979a947c2STobias Grosser     Sizes.push_back(Res);
145079a947c2STobias Grosser   }
145179a947c2STobias Grosser 
145279a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
145379a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
145479a947c2STobias Grosser 
145579a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
145679a947c2STobias Grosser }
145779a947c2STobias Grosser 
1458a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1459a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1460a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1461a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1462a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1463a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1464a90be207SSiddharth Bhat }
1465a90be207SSiddharth Bhat 
146657693272STobias Grosser Value *
146757693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
146857693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1469a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1470a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1471a90be207SSiddharth Bhat 
1472a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
147379a947c2STobias Grosser 
147479a947c2STobias Grosser   BasicBlock *EntryBlock =
147579a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
147667726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
147779a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
147867726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
147967726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
148079a947c2STobias Grosser 
148179a947c2STobias Grosser   int Index = 0;
148279a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
148379a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
148479a947c2STobias Grosser       continue;
148579a947c2STobias Grosser 
148679a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
148779a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
148879a947c2STobias Grosser 
1489a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1490a90be207SSiddharth Bhat 
1491abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1492abed4969SSiddharth Bhat     if (ManagedMemory) {
1493abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1494abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1495abed4969SSiddharth Bhat     } else {
1496abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
149779a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1498abed4969SSiddharth Bhat     }
1499abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1500abed4969SSiddharth Bhat                                   "initialized");
1501aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1502aaabbbf8STobias Grosser 
1503aaabbbf8STobias Grosser     if (Offset) {
1504aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1505aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1506aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1507aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1508aaabbbf8STobias Grosser     }
1509fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1510fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1511aaabbbf8STobias Grosser 
1512fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1513abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1514abed4969SSiddharth Bhat       if (ManagedMemory)
1515abed4969SSiddharth Bhat         ValPtr = DevArray;
1516abed4969SSiddharth Bhat       else
1517abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1518abed4969SSiddharth Bhat 
1519abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1520abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1521fe74a7a1STobias Grosser       Value *ValPtrCast =
1522fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1523fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1524fe74a7a1STobias Grosser     } else {
152567726b32STobias Grosser       Instruction *Param =
152667726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
152767726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
152879a947c2STobias Grosser                          EntryBlock->getTerminator());
152979a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
153079a947c2STobias Grosser       Value *ParamTyped =
153179a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
153279a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1533fe74a7a1STobias Grosser     }
153479a947c2STobias Grosser     Index++;
153579a947c2STobias Grosser   }
153679a947c2STobias Grosser 
1537a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1538a490147cSTobias Grosser 
1539a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1540a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1541a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1542a490147cSTobias Grosser     isl_id_free(Id);
1543a90be207SSiddharth Bhat 
1544a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1545a90be207SSiddharth Bhat 
154667726b32STobias Grosser     Instruction *Param =
154767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
154867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1549a490147cSTobias Grosser                        EntryBlock->getTerminator());
1550a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1551a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1552a490147cSTobias Grosser     Index++;
1553a490147cSTobias Grosser   }
1554a490147cSTobias Grosser 
1555d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1556d8b94bcaSTobias Grosser 
1557d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1558d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1559d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1560a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1561a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1562d8b94bcaSTobias Grosser     isl_id_free(Id);
1563a90be207SSiddharth Bhat 
1564a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1565a90be207SSiddharth Bhat 
156667726b32STobias Grosser     Instruction *Param =
156767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
156867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1569d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1570d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1571a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1572d8b94bcaSTobias Grosser     Index++;
1573d8b94bcaSTobias Grosser   }
1574d8b94bcaSTobias Grosser 
157557693272STobias Grosser   for (auto Val : SubtreeValues) {
1576a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1577a90be207SSiddharth Bhat 
157867726b32STobias Grosser     Instruction *Param =
157967726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
158067726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
158157693272STobias Grosser                        EntryBlock->getTerminator());
158257693272STobias Grosser     Builder.CreateStore(Val, Param);
1583a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1584a90be207SSiddharth Bhat     Index++;
1585a90be207SSiddharth Bhat   }
1586a90be207SSiddharth Bhat 
1587a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1588a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1589a90be207SSiddharth Bhat     Instruction *Param =
1590a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1591a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1592a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1593a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1594a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
159557693272STobias Grosser     Index++;
159657693272STobias Grosser   }
159757693272STobias Grosser 
159879a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
159979a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
160079a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
160179a947c2STobias Grosser }
160279a947c2STobias Grosser 
1603f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1604f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1605f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1606f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1607f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1608f291c8d5SSiddharth Bhat     if (!Clone)
1609f291c8d5SSiddharth Bhat       Clone =
1610f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1611f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1612f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1613f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1614f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1615f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1616f291c8d5SSiddharth Bhat   }
1617f291c8d5SSiddharth Bhat }
161832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
161932837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
162032837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
162132837fe3STobias Grosser   isl_id_free(Id);
162232837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
162332837fe3STobias Grosser 
1624bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1625bc653f20STobias Grosser     DeepestParallel =
1626bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1627bc653f20STobias Grosser   else
1628bc653f20STobias Grosser     DeepestSequential =
1629bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1630bc653f20STobias Grosser 
1631c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1632c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1633c1c6a2a6STobias Grosser 
1634f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1635f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1636f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1637edb885cbSTobias Grosser 
163832837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
163932837fe3STobias Grosser 
164032837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1641472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1642edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1643587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1644b06ff457STobias Grosser   ScalarMap.clear();
164532837fe3STobias Grosser 
1646edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1647edb885cbSTobias Grosser 
1648edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1649edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1650edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1651edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1652edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1653edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1654edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1655edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1656edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1657edb885cbSTobias Grosser     SubtreeValues.insert(V);
1658edb885cbSTobias Grosser   }
1659edb885cbSTobias Grosser 
1660f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1661f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
166232837fe3STobias Grosser 
166359ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
166459ab0705STobias Grosser 
166551dfc275STobias Grosser   finalizeKernelArguments(Kernel);
166674dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1667c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
166874dc3cb4STobias Grosser   clearDominators(F);
166974dc3cb4STobias Grosser   clearScalarEvolution(F);
167074dc3cb4STobias Grosser   clearLoops(F);
167174dc3cb4STobias Grosser 
1672472f9654STobias Grosser   IDToValue = HostIDs;
167332837fe3STobias Grosser 
1674b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1675b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1676edb885cbSTobias Grosser   EscapeMap.clear();
1677edb885cbSTobias Grosser   IDToSAI.clear();
167874dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
167974dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
16804d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
168174dc3cb4STobias Grosser   LocalArrays.clear();
1682edb885cbSTobias Grosser 
168351dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
168451dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
168557693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
168679a947c2STobias Grosser 
168779f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
168857793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
168957793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
169057793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
169179a947c2STobias Grosser 
169279a947c2STobias Grosser   Value *GridDimX, *GridDimY;
169379a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
169479a947c2STobias Grosser 
169579a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
169679a947c2STobias Grosser                          BlockDimZ, Parameters);
169757793596STobias Grosser   createCallFreeKernel(GPUKernel);
1698b513b491STobias Grosser 
1699b513b491STobias Grosser   for (auto Id : KernelIds)
1700b513b491STobias Grosser     isl_id_free(Id);
1701b513b491STobias Grosser 
1702b513b491STobias Grosser   KernelIds.clear();
170332837fe3STobias Grosser }
170432837fe3STobias Grosser 
170532837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
170632837fe3STobias Grosser ///
170732837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
170832837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1709d277fedaSSiddharth Bhat   std::string Ret = "";
171032837fe3STobias Grosser 
1711d277fedaSSiddharth Bhat   if (!is64Bit) {
1712d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1713d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1714d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1715d277fedaSSiddharth Bhat   } else {
1716d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1717d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1718d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1719d277fedaSSiddharth Bhat   }
172032837fe3STobias Grosser 
172132837fe3STobias Grosser   return Ret;
172232837fe3STobias Grosser }
172332837fe3STobias Grosser 
1724edb885cbSTobias Grosser Function *
1725edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1726edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
172732837fe3STobias Grosser   std::vector<Type *> Args;
172879f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
172932837fe3STobias Grosser 
173032837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
173132837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
173232837fe3STobias Grosser       continue;
173332837fe3STobias Grosser 
1734fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1735fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1736fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1737fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1738fe74a7a1STobias Grosser     } else {
1739d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1740d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
174132837fe3STobias Grosser     }
1742fe74a7a1STobias Grosser   }
174332837fe3STobias Grosser 
1744f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1745f6044bd0STobias Grosser 
1746f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1747f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1748f6044bd0STobias Grosser 
1749c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1750c84a1995STobias Grosser 
1751cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1752cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1753cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1754cf66ef26STobias Grosser     isl_id_free(Id);
1755cf66ef26STobias Grosser     Args.push_back(Val->getType());
1756cf66ef26STobias Grosser   }
1757c84a1995STobias Grosser 
1758edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1759edb885cbSTobias Grosser     Args.push_back(V->getType());
1760edb885cbSTobias Grosser 
176132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
176232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
176332837fe3STobias Grosser                               GPUModule.get());
176417f01968SSiddharth Bhat 
176517f01968SSiddharth Bhat   switch (Arch) {
176617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
176732837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
176817f01968SSiddharth Bhat     break;
176917f01968SSiddharth Bhat   }
177032837fe3STobias Grosser 
177132837fe3STobias Grosser   auto Arg = FN->arg_begin();
177232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
177332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
177432837fe3STobias Grosser       continue;
177532837fe3STobias Grosser 
1776edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1777edb885cbSTobias Grosser 
1778edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1779edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1780edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1781edb885cbSTobias Grosser     Value *Val = &*Arg;
1782edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1783edb885cbSTobias Grosser     isl_ast_build *Build =
1784edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1785f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1786edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1787edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1788*9e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1789edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1790edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1791edb885cbSTobias Grosser     }
1792edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
17934d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
179474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1795edb885cbSTobias Grosser 
1796edb885cbSTobias Grosser     isl_ast_build_free(Build);
1797b513b491STobias Grosser     KernelIds.push_back(Id);
1798edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
179932837fe3STobias Grosser     Arg++;
180032837fe3STobias Grosser   }
180132837fe3STobias Grosser 
1802f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1803f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1804f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1805f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1806f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1807f6044bd0STobias Grosser     Arg++;
1808f6044bd0STobias Grosser   }
1809f6044bd0STobias Grosser 
1810c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1811c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1812c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
181312453403STobias Grosser     Value *Val = IDToValue[Id];
181412453403STobias Grosser     ValueMap[Val] = &*Arg;
1815c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1816c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1817c84a1995STobias Grosser     Arg++;
1818c84a1995STobias Grosser   }
1819c84a1995STobias Grosser 
1820edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1821edb885cbSTobias Grosser     Arg->setName(V->getName());
1822edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1823edb885cbSTobias Grosser     Arg++;
1824edb885cbSTobias Grosser   }
1825edb885cbSTobias Grosser 
182632837fe3STobias Grosser   return FN;
182732837fe3STobias Grosser }
182832837fe3STobias Grosser 
1829472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
183017f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
183117f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1832472f9654STobias Grosser 
183317f01968SSiddharth Bhat   switch (Arch) {
183417f01968SSiddharth Bhat   case GPUArch::NVPTX64:
183517f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
183617f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
183717f01968SSiddharth Bhat 
183817f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
183917f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
184017f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
184117f01968SSiddharth Bhat     break;
184217f01968SSiddharth Bhat   }
1843472f9654STobias Grosser 
1844472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1845472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1846472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1847472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1848472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1849472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1850472f9654STobias Grosser     IDToValue[Id] = Val;
1851472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1852472f9654STobias Grosser   };
1853472f9654STobias Grosser 
1854472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1855472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1856472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1857472f9654STobias Grosser   }
1858472f9654STobias Grosser 
1859472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1860472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1861472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1862472f9654STobias Grosser   }
1863472f9654STobias Grosser }
1864472f9654STobias Grosser 
186500bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
186600bb5a99STobias Grosser   auto Arg = FN->arg_begin();
186700bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
186800bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
186900bb5a99STobias Grosser       continue;
187000bb5a99STobias Grosser 
187100bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
187200bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
187300bb5a99STobias Grosser     isl_id_free(Id);
187400bb5a99STobias Grosser 
187500bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
187600bb5a99STobias Grosser       Arg++;
187700bb5a99STobias Grosser       continue;
187800bb5a99STobias Grosser     }
187900bb5a99STobias Grosser 
1880fe74a7a1STobias Grosser     Value *Val = &*Arg;
1881fe74a7a1STobias Grosser 
1882fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
188300bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1884fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1885fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1886fe74a7a1STobias Grosser     }
1887fe74a7a1STobias Grosser 
1888fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
188900bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
189000bb5a99STobias Grosser 
189100bb5a99STobias Grosser     Arg++;
189200bb5a99STobias Grosser   }
189300bb5a99STobias Grosser }
189400bb5a99STobias Grosser 
189551dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
189651dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
189751dfc275STobias Grosser   auto Arg = FN->arg_begin();
189851dfc275STobias Grosser 
189951dfc275STobias Grosser   bool StoredScalar = false;
190051dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
190151dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
190251dfc275STobias Grosser       continue;
190351dfc275STobias Grosser 
190451dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
190551dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
190651dfc275STobias Grosser     isl_id_free(Id);
190751dfc275STobias Grosser 
190851dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
190951dfc275STobias Grosser       Arg++;
191051dfc275STobias Grosser       continue;
191151dfc275STobias Grosser     }
191251dfc275STobias Grosser 
191351dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
191451dfc275STobias Grosser       Arg++;
191551dfc275STobias Grosser       continue;
191651dfc275STobias Grosser     }
191751dfc275STobias Grosser 
191851dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
191951dfc275STobias Grosser     Value *ArgPtr = &*Arg;
192051dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
192151dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
192251dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
192351dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
192451dfc275STobias Grosser     StoredScalar = true;
192551dfc275STobias Grosser 
192651dfc275STobias Grosser     Arg++;
192751dfc275STobias Grosser   }
192851dfc275STobias Grosser 
192951dfc275STobias Grosser   if (StoredScalar)
193051dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
193151dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
193251dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
193351dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
193451dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
193551dfc275STobias Grosser       BuildSuccessful = 0;
193651dfc275STobias Grosser }
193751dfc275STobias Grosser 
1938b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1939b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1940b513b491STobias Grosser 
1941b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1942b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1943b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1944b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1945b513b491STobias Grosser 
1946f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1947b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1948b513b491STobias Grosser 
1949f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1950928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1951b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1952f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1953b513b491STobias Grosser       isl_val_free(Val);
1954b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1955928d7573STobias Grosser     }
1956928d7573STobias Grosser 
1957928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1958928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1959928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1960928d7573STobias Grosser       isl_val_free(Val);
1961b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1962b513b491STobias Grosser     }
1963b513b491STobias Grosser 
1964130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1965130ca30fSTobias Grosser     Value *Allocation;
1966130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1967130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1968130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1969130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1970130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1971f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1972f919d8b3STobias Grosser 
1973130ca30fSTobias Grosser       Allocation = GlobalVar;
1974130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1975130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1976130ca30fSTobias Grosser     } else {
1977130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1978130ca30fSTobias Grosser     }
19794d5a9172STobias Grosser     SAI =
19804d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1981b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1982130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1983130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1984b513b491STobias Grosser     KernelIds.push_back(Id);
1985b513b491STobias Grosser     IDToSAI[Id] = SAI;
1986b513b491STobias Grosser   }
1987b513b491STobias Grosser }
1988b513b491STobias Grosser 
1989f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
1990f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1991f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
199279f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
199332837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
199417f01968SSiddharth Bhat 
199517f01968SSiddharth Bhat   switch (Arch) {
199617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
199717f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
199832837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
199917f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
200017f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
200132837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
200217f01968SSiddharth Bhat     break;
200317f01968SSiddharth Bhat   }
200432837fe3STobias Grosser 
2005edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
200632837fe3STobias Grosser 
200759ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
200832837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
200932837fe3STobias Grosser 
201059ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
201159ab0705STobias Grosser 
201232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
201332837fe3STobias Grosser   Builder.CreateRetVoid();
201432837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2015472f9654STobias Grosser 
2016629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2017629109b6STobias Grosser 
201800bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2019b513b491STobias Grosser   createKernelVariables(Kernel, FN);
2020472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
202132837fe3STobias Grosser }
202232837fe3STobias Grosser 
202374dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
202417f01968SSiddharth Bhat   llvm::Triple GPUTriple;
202517f01968SSiddharth Bhat 
202617f01968SSiddharth Bhat   switch (Arch) {
202717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
202817f01968SSiddharth Bhat     switch (Runtime) {
202917f01968SSiddharth Bhat     case GPURuntime::CUDA:
203017f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
203117f01968SSiddharth Bhat       break;
203217f01968SSiddharth Bhat     case GPURuntime::OpenCL:
203317f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
203417f01968SSiddharth Bhat       break;
203517f01968SSiddharth Bhat     }
203617f01968SSiddharth Bhat     break;
203717f01968SSiddharth Bhat   }
203817f01968SSiddharth Bhat 
203974dc3cb4STobias Grosser   std::string ErrMsg;
204074dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
204174dc3cb4STobias Grosser 
204274dc3cb4STobias Grosser   if (!GPUTarget) {
204374dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
204474dc3cb4STobias Grosser     return "";
204574dc3cb4STobias Grosser   }
204674dc3cb4STobias Grosser 
204774dc3cb4STobias Grosser   TargetOptions Options;
204874dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
204917f01968SSiddharth Bhat 
205017f01968SSiddharth Bhat   std::string subtarget;
205117f01968SSiddharth Bhat 
205217f01968SSiddharth Bhat   switch (Arch) {
205317f01968SSiddharth Bhat   case GPUArch::NVPTX64:
205417f01968SSiddharth Bhat     subtarget = CudaVersion;
205517f01968SSiddharth Bhat     break;
205617f01968SSiddharth Bhat   }
205717f01968SSiddharth Bhat 
205817f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
205917f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
206074dc3cb4STobias Grosser 
206174dc3cb4STobias Grosser   SmallString<0> ASMString;
206274dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
206374dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
206474dc3cb4STobias Grosser 
206574dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
206674dc3cb4STobias Grosser 
206774dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
206874dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
206974dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
207074dc3cb4STobias Grosser     return "";
207174dc3cb4STobias Grosser   }
207274dc3cb4STobias Grosser 
207374dc3cb4STobias Grosser   PM.run(*GPUModule);
207474dc3cb4STobias Grosser 
207574dc3cb4STobias Grosser   return ASMStream.str();
207674dc3cb4STobias Grosser }
207774dc3cb4STobias Grosser 
207857793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
207965d7f72fSSiddharth Bhat 
20805857b701STobias Grosser   if (verifyModule(*GPUModule)) {
208165d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
208265d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
208365d7f72fSSiddharth Bhat 
208465d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
208565d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
208665d7f72fSSiddharth Bhat 
20875857b701STobias Grosser     BuildSuccessful = false;
20885857b701STobias Grosser     return "";
20895857b701STobias Grosser   }
209032837fe3STobias Grosser 
209132837fe3STobias Grosser   if (DumpKernelIR)
209232837fe3STobias Grosser     outs() << *GPUModule << "\n";
209332837fe3STobias Grosser 
20949a18d559STobias Grosser   // Optimize module.
20959a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
20969a18d559STobias Grosser   PassManagerBuilder PassBuilder;
20979a18d559STobias Grosser   PassBuilder.OptLevel = 3;
20989a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
20999a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
21009a18d559STobias Grosser   OptPasses.run(*GPUModule);
21019a18d559STobias Grosser 
210274dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
210374dc3cb4STobias Grosser 
210474dc3cb4STobias Grosser   if (DumpKernelASM)
210574dc3cb4STobias Grosser     outs() << Assembly << "\n";
210674dc3cb4STobias Grosser 
210732837fe3STobias Grosser   GPUModule.release();
2108472f9654STobias Grosser   KernelIDs.clear();
210957793596STobias Grosser 
211057793596STobias Grosser   return Assembly;
211132837fe3STobias Grosser }
211232837fe3STobias Grosser 
21139dfe4e7cSTobias Grosser namespace {
21149dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
21159dfe4e7cSTobias Grosser public:
21169dfe4e7cSTobias Grosser   static char ID;
21179dfe4e7cSTobias Grosser 
211817f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
211917f01968SSiddharth Bhat 
212017f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
212117f01968SSiddharth Bhat 
2122e938517eSTobias Grosser   /// The scop that is currently processed.
2123e938517eSTobias Grosser   Scop *S;
2124e938517eSTobias Grosser 
212538fc0aedSTobias Grosser   LoopInfo *LI;
212638fc0aedSTobias Grosser   DominatorTree *DT;
212738fc0aedSTobias Grosser   ScalarEvolution *SE;
212838fc0aedSTobias Grosser   const DataLayout *DL;
212938fc0aedSTobias Grosser   RegionInfo *RI;
213038fc0aedSTobias Grosser 
21319dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
21329dfe4e7cSTobias Grosser 
2133e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2134e938517eSTobias Grosser   ///
2135e938517eSTobias Grosser   /// @returns The compilation options.
2136e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2137e938517eSTobias Grosser     auto DebugOptions =
2138e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2139e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2140e938517eSTobias Grosser 
2141e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2142e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2143e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2144e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
21458950ceadSTobias Grosser     DebugOptions->verbose = false;
2146e938517eSTobias Grosser 
2147e938517eSTobias Grosser     Options->debug = DebugOptions;
2148e938517eSTobias Grosser 
2149*9e3db2b7SSiddharth Bhat     Options->group_chains = false;
2150e938517eSTobias Grosser     Options->reschedule = true;
2151e938517eSTobias Grosser     Options->scale_tile_loops = false;
2152e938517eSTobias Grosser     Options->wrap = false;
2153e938517eSTobias Grosser 
2154e938517eSTobias Grosser     Options->non_negative_parameters = false;
2155e938517eSTobias Grosser     Options->ctx = nullptr;
2156e938517eSTobias Grosser     Options->sizes = nullptr;
2157e938517eSTobias Grosser 
2158*9e3db2b7SSiddharth Bhat     Options->tile = true;
21594eaedde5STobias Grosser     Options->tile_size = 32;
21604eaedde5STobias Grosser 
2161*9e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
2162*9e3db2b7SSiddharth Bhat 
2163130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2164b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2165b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2166e938517eSTobias Grosser 
2167e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2168e938517eSTobias Grosser     Options->openmp = false;
2169e938517eSTobias Grosser     Options->linearize_device_arrays = true;
2170*9e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2171e938517eSTobias Grosser 
2172*9e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
2173*9e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
2174*9e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
2175*9e3db2b7SSiddharth Bhat 
2176*9e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
2177*9e3db2b7SSiddharth Bhat     Options->hybrid = false;
2178e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2179e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2180e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2181e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2182e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2183e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2184e938517eSTobias Grosser 
2185e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2186e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2187e938517eSTobias Grosser 
2188e938517eSTobias Grosser     return Options;
2189e938517eSTobias Grosser   }
2190e938517eSTobias Grosser 
2191f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2192f384594dSTobias Grosser   ///
2193f384594dSTobias Grosser   /// Instead of a normal access of the form:
2194f384594dSTobias Grosser   ///
2195f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2196f384594dSTobias Grosser   ///
2197f384594dSTobias Grosser   /// a tagged access has the form
2198f384594dSTobias Grosser   ///
2199f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2200f384594dSTobias Grosser   ///
2201f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2202f384594dSTobias Grosser   /// triggered the access.
2203f384594dSTobias Grosser   ///
2204f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2205f384594dSTobias Grosser   ///
2206f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2207f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2208f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2209f384594dSTobias Grosser 
2210f384594dSTobias Grosser     for (auto &Stmt : *S)
2211f384594dSTobias Grosser       for (auto &Acc : Stmt)
2212f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
2213f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
2214f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2215f384594dSTobias Grosser 
2216f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2217f384594dSTobias Grosser           Space = isl_space_range(Space);
2218f384594dSTobias Grosser           Space = isl_space_from_range(Space);
22196293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2220f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2221f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2222f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2223f384594dSTobias Grosser         }
2224f384594dSTobias Grosser 
2225f384594dSTobias Grosser     return Accesses;
2226f384594dSTobias Grosser   }
2227f384594dSTobias Grosser 
2228f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2229f384594dSTobias Grosser   ///
2230f384594dSTobias Grosser   /// @see getTaggedAccesses
2231f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2232f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2233f384594dSTobias Grosser   }
2234f384594dSTobias Grosser 
2235f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2236f384594dSTobias Grosser   ///
2237f384594dSTobias Grosser   /// @see getTaggedAccesses
2238f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2239f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2240f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2241f384594dSTobias Grosser   }
2242f384594dSTobias Grosser 
2243f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2244f384594dSTobias Grosser   ///
2245f384594dSTobias Grosser   /// @see getTaggedAccesses
2246f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2247f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2248f384594dSTobias Grosser   }
2249f384594dSTobias Grosser 
2250aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2251aef5196fSTobias Grosser   ///
2252aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2253aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2254aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2255aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2256aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2257aef5196fSTobias Grosser   /// the data format that ppcg expects.
2258aef5196fSTobias Grosser   ///
2259aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2260aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2261aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2262bd81a7eeSTobias Grosser         S->getIslCtx(),
2263bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2264aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2265aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
2266aef5196fSTobias Grosser 
2267aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2268aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2269aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2270aef5196fSTobias Grosser     }
2271aef5196fSTobias Grosser 
2272aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
2273d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
2274aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2275aef5196fSTobias Grosser     }
2276aef5196fSTobias Grosser 
2277aef5196fSTobias Grosser     isl_space_free(Space);
2278aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2279aef5196fSTobias Grosser 
2280aef5196fSTobias Grosser     return Names;
2281aef5196fSTobias Grosser   }
2282aef5196fSTobias Grosser 
2283e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2284e938517eSTobias Grosser   ///
2285f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2286f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2287f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2288f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2289e938517eSTobias Grosser   ///
2290e938517eSTobias Grosser   /// @returns A new ppcg scop.
2291e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
2292*9e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
2293*9e3db2b7SSiddharth Bhat 
2294e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2295e938517eSTobias Grosser 
2296e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2297a82f2d26SSiddharth Bhat     // enable live range reordering
2298a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2299e938517eSTobias Grosser 
2300e938517eSTobias Grosser     PPCGScop->start = 0;
2301e938517eSTobias Grosser     PPCGScop->end = 0;
2302e938517eSTobias Grosser 
2303f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2304f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
2305*9e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
2306*9e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2307f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2308f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2309e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2310f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2311f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2312f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2313f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2314e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
2315*9e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
2316*9e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
2317*9e3db2b7SSiddharth Bhat 
2318e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2319a82f2d26SSiddharth Bhat     PPCGScop->independence =
2320a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2321e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2322e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2323e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2324e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2325e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2326e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2327e938517eSTobias Grosser 
2328f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2329a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2330a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2331a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2332a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2333a82f2d26SSiddharth Bhat 
2334a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2335e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2336e938517eSTobias Grosser 
2337f384594dSTobias Grosser     compute_tagger(PPCGScop);
2338f384594dSTobias Grosser     compute_dependences(PPCGScop);
2339*9e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2340f384594dSTobias Grosser 
2341e938517eSTobias Grosser     return PPCGScop;
2342e938517eSTobias Grosser   }
2343e938517eSTobias Grosser 
2344a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
234560f63b49STobias Grosser   ///
234660f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
234760f63b49STobias Grosser   ///
234860f63b49STobias Grosser   /// @returns A list of array accesses.
234960f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
235060f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
235160f63b49STobias Grosser 
235260f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
235360f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
235460f63b49STobias Grosser       Access->read = Acc->isRead();
235560f63b49STobias Grosser       Access->write = Acc->isWrite();
235660f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
235760f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
235860f63b49STobias Grosser       Space = isl_space_range(Space);
235960f63b49STobias Grosser       Space = isl_space_from_range(Space);
23606293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
236160f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
236260f63b49STobias Grosser       Access->tagged_access =
236360f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2364b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
236560f63b49STobias Grosser       Access->ref_id = Acc->getId();
236660f63b49STobias Grosser       Access->next = Accesses;
2367b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
236860f63b49STobias Grosser       Accesses = Access;
236960f63b49STobias Grosser     }
237060f63b49STobias Grosser 
237160f63b49STobias Grosser     return Accesses;
237260f63b49STobias Grosser   }
237360f63b49STobias Grosser 
237469b46751STobias Grosser   /// Collect the list of GPU statements.
237569b46751STobias Grosser   ///
237669b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
237769b46751STobias Grosser   /// as well as a list with all memory accesses.
237869b46751STobias Grosser   ///
237969b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
238069b46751STobias Grosser   ///
238169b46751STobias Grosser   /// @returns A linked-list of statements.
238269b46751STobias Grosser   gpu_stmt *getStatements() {
238369b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
238469b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
238569b46751STobias Grosser 
238669b46751STobias Grosser     int i = 0;
238769b46751STobias Grosser     for (auto &Stmt : *S) {
238869b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
238969b46751STobias Grosser 
239069b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
239169b46751STobias Grosser 
239269b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
239369b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
239460f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
239569b46751STobias Grosser       i++;
239669b46751STobias Grosser     }
239769b46751STobias Grosser 
239869b46751STobias Grosser     return Stmts;
239969b46751STobias Grosser   }
240069b46751STobias Grosser 
240160f63b49STobias Grosser   /// Derive the extent of an array.
240260f63b49STobias Grosser   ///
2403d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2404d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2405d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2406d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2407d58acf86STobias Grosser   /// subscript value for the first dimension.
240860f63b49STobias Grosser   ///
240960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
241060f63b49STobias Grosser   ///
241160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
241260f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2413d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
241460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
241560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2416d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
241760f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2418d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2419d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2420d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2421d58acf86STobias Grosser 
2422d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2423d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2424d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2425d58acf86STobias Grosser     }
2426d58acf86STobias Grosser 
2427d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2428d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2429d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2430d58acf86STobias Grosser     }
2431d58acf86STobias Grosser 
243260f63b49STobias Grosser     isl_set *AccessSet =
243360f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
243460f63b49STobias Grosser 
2435d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2436d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2437d58acf86STobias Grosser 
2438d58acf86STobias Grosser     isl_pw_aff *Val =
2439d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2440d58acf86STobias Grosser 
2441d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2442d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2443d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2444d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2445d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2446d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2447d58acf86STobias Grosser     OuterMin =
2448d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2449d58acf86STobias Grosser     OuterMax =
2450d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2451d58acf86STobias Grosser 
2452d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2453d58acf86STobias Grosser 
2454d58acf86STobias Grosser     Extent = isl_set_intersect(
2455d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2456d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2457d58acf86STobias Grosser 
2458d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2459d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2460d58acf86STobias Grosser 
2461b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2462d58acf86STobias Grosser       isl_pw_aff *PwAff =
2463d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2464b7f68b8cSSiddharth Bhat 
2465b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2466b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2467b7f68b8cSSiddharth Bhat       if (!PwAff) {
2468b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2469b7f68b8cSSiddharth Bhat         continue;
2470b7f68b8cSSiddharth Bhat       }
2471b7f68b8cSSiddharth Bhat 
2472d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2473d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2474d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2475d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2476d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2477d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2478d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2479d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2480d58acf86STobias Grosser     }
2481d58acf86STobias Grosser 
2482d58acf86STobias Grosser     return Extent;
248360f63b49STobias Grosser   }
248460f63b49STobias Grosser 
248560f63b49STobias Grosser   /// Derive the bounds of an array.
248660f63b49STobias Grosser   ///
248760f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
248860f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
248960f63b49STobias Grosser   /// ScopArrayInfo.
249060f63b49STobias Grosser   ///
249160f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
249260f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
249360f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2494*9e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
2495*9e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
2496*9e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
2497*9e3db2b7SSiddharth Bhat 
2498*9e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
2499*9e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
2500*9e3db2b7SSiddharth Bhat 
250160f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
250202293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
250302293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
250402293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
250502293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
250602293ed7STobias Grosser         isl_set_free(Dom);
2507*9e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2508*9e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
2509*9e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
2510*9e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
251102293ed7STobias Grosser       } else {
251260f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
251360f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
251460f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
251560f63b49STobias Grosser         isl_set_free(Dom);
251660f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
251702293ed7STobias Grosser         isl_local_space *LS =
251802293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
251960f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
252060f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
252160f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
252260f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
2523*9e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
2524*9e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
2525*9e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
252660f63b49STobias Grosser       }
252702293ed7STobias Grosser     }
252860f63b49STobias Grosser 
252960f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
253060f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
253160f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
253260f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
253360f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2534*9e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
2535*9e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
2536*9e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
253760f63b49STobias Grosser     }
2538*9e3db2b7SSiddharth Bhat 
2539*9e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
2540*9e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2541*9e3db2b7SSiddharth Bhat 
2542*9e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
2543*9e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
2544*9e3db2b7SSiddharth Bhat 
2545*9e3db2b7SSiddharth Bhat     PPCGArray.bound =
2546*9e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
2547*9e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
254860f63b49STobias Grosser   }
254960f63b49STobias Grosser 
255060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
255160f63b49STobias Grosser   ///
255260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
255360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
255460f63b49STobias Grosser     int i = 0;
2555d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
255660f63b49STobias Grosser       std::string TypeName;
255760f63b49STobias Grosser       raw_string_ostream OS(TypeName);
255860f63b49STobias Grosser 
255960f63b49STobias Grosser       OS << *Array->getElementType();
256060f63b49STobias Grosser       TypeName = OS.str();
256160f63b49STobias Grosser 
256260f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
256360f63b49STobias Grosser 
256460f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
256560f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
256660f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
256760f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
256860f63b49STobias Grosser       PPCGArray.extent = nullptr;
256960f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
257060f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
257160f63b49STobias Grosser       PPCGArray.n_ref = 0;
257260f63b49STobias Grosser       PPCGArray.refs = nullptr;
257360f63b49STobias Grosser       PPCGArray.accessed = true;
2574fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2575fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
257660f63b49STobias Grosser       PPCGArray.has_compound_element = false;
257760f63b49STobias Grosser       PPCGArray.local = false;
257860f63b49STobias Grosser       PPCGArray.declare_local = false;
257960f63b49STobias Grosser       PPCGArray.global = false;
258060f63b49STobias Grosser       PPCGArray.linearize = false;
258160f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
258213c78e4dSTobias Grosser       PPCGArray.user = Array;
258360f63b49STobias Grosser 
2584*9e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
258560f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
25862d010dafSTobias Grosser       i++;
2587b9fc860aSTobias Grosser 
2588b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
258960f63b49STobias Grosser     }
259060f63b49STobias Grosser   }
259160f63b49STobias Grosser 
259260f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
259360f63b49STobias Grosser   ///
259460f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
259560f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
259660f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
259760f63b49STobias Grosser 
2598d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
259960f63b49STobias Grosser       isl_space *Space = Array->getSpace();
260060f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
260160f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
260260f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
260360f63b49STobias Grosser     }
260460f63b49STobias Grosser 
260560f63b49STobias Grosser     return Maps;
260660f63b49STobias Grosser   }
260760f63b49STobias Grosser 
2608e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2609e938517eSTobias Grosser   ///
2610a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2611e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2612e938517eSTobias Grosser 
2613e938517eSTobias Grosser     if (!PPCGScop)
2614e938517eSTobias Grosser       return nullptr;
2615e938517eSTobias Grosser 
2616e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2617e938517eSTobias Grosser 
2618e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2619e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2620aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
262160f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
262260f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
262360f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
262460f63b49STobias Grosser     PPCGProg->tagged_must_kill =
262560f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
262660f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
262760f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2628*9e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2629e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2630a82f2d26SSiddharth Bhat 
2631a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2632a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2633a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2634a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2635a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2636a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
263769b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
263869b46751STobias Grosser     PPCGProg->stmts = getStatements();
263960f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
264060f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
264160f63b49STobias Grosser                                        PPCGProg->n_array);
264260f63b49STobias Grosser 
264360f63b49STobias Grosser     createArrays(PPCGProg);
2644e938517eSTobias Grosser 
2645d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2646e938517eSTobias Grosser     return PPCGProg;
2647e938517eSTobias Grosser   }
2648e938517eSTobias Grosser 
264969b46751STobias Grosser   struct PrintGPUUserData {
265069b46751STobias Grosser     struct cuda_info *CudaInfo;
265169b46751STobias Grosser     struct gpu_prog *PPCGProg;
265269b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
265369b46751STobias Grosser   };
265469b46751STobias Grosser 
265569b46751STobias Grosser   /// Print a user statement node in the host code.
265669b46751STobias Grosser   ///
265769b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
265869b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
265969b46751STobias Grosser   /// host ast.
266069b46751STobias Grosser   ///
266169b46751STobias Grosser   /// @param P The printer to print to
266269b46751STobias Grosser   /// @param Options The printing options to use
266369b46751STobias Grosser   /// @param Node The node to print
266469b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
266569b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
266669b46751STobias Grosser   ///
266769b46751STobias Grosser   /// @returns A printer to which the output has been printed.
266869b46751STobias Grosser   static __isl_give isl_printer *
266969b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
267069b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
267169b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
267269b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
267369b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
267469b46751STobias Grosser 
267569b46751STobias Grosser     if (Id) {
267620251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
267720251734STobias Grosser 
267820251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
267920251734STobias Grosser       // otherwise try to call pet functionality that is not available in
268020251734STobias Grosser       // Polly.
268120251734STobias Grosser       if (IsUser) {
268220251734STobias Grosser         P = isl_printer_start_line(P);
268320251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
268420251734STobias Grosser         P = isl_printer_end_line(P);
268520251734STobias Grosser         isl_id_free(Id);
268620251734STobias Grosser         isl_ast_print_options_free(Options);
268720251734STobias Grosser         return P;
268820251734STobias Grosser       }
268920251734STobias Grosser 
269069b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
269169b46751STobias Grosser       isl_id_free(Id);
269269b46751STobias Grosser       Data->Kernels.push_back(Kernel);
269369b46751STobias Grosser     }
269469b46751STobias Grosser 
269569b46751STobias Grosser     return print_host_user(P, Options, Node, User);
269669b46751STobias Grosser   }
269769b46751STobias Grosser 
269869b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
269969b46751STobias Grosser   ///
270069b46751STobias Grosser   /// @param Kernel The kernel to print
270169b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
270269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
270369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
270469b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
270569b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
270669b46751STobias Grosser     char *String = isl_printer_get_str(P);
270769b46751STobias Grosser     printf("%s\n", String);
270869b46751STobias Grosser     free(String);
270969b46751STobias Grosser     isl_printer_free(P);
271069b46751STobias Grosser   }
271169b46751STobias Grosser 
271269b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
271369b46751STobias Grosser   ///
271469b46751STobias Grosser   /// @param Tree An AST describing GPU code
271569b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
271669b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
271769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
271869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
271969b46751STobias Grosser 
272069b46751STobias Grosser     PrintGPUUserData Data;
272169b46751STobias Grosser     Data.PPCGProg = PPCGProg;
272269b46751STobias Grosser 
272369b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
272469b46751STobias Grosser     Options =
272569b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
272669b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
272769b46751STobias Grosser     char *String = isl_printer_get_str(P);
272869b46751STobias Grosser     printf("# host\n");
272969b46751STobias Grosser     printf("%s\n", String);
273069b46751STobias Grosser     free(String);
273169b46751STobias Grosser     isl_printer_free(P);
273269b46751STobias Grosser 
273369b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
273469b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
273569b46751STobias Grosser       printKernel(Kernel);
273669b46751STobias Grosser     }
273769b46751STobias Grosser   }
273869b46751STobias Grosser 
2739f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2740f384594dSTobias Grosser   //
2741f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2742f384594dSTobias Grosser   //
2743f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2744f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2745f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2746f384594dSTobias Grosser   //
2747f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2748f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2749f384594dSTobias Grosser   // strategy directly from this pass.
2750f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2751f384594dSTobias Grosser 
2752f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2753f384594dSTobias Grosser 
2754f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2755f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2756f384594dSTobias Grosser     PPCGGen->print = nullptr;
2757f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
275860c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2759f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2760f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2761f384594dSTobias Grosser     PPCGGen->types.n = 0;
2762f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2763f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2764f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2765f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2766f384594dSTobias Grosser 
2767f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2768f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2769f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
27702341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2771f384594dSTobias Grosser 
2772f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2773f384594dSTobias Grosser 
2774aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2775aef5196fSTobias Grosser 
277669b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2777aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
277869b46751STobias Grosser     } else {
2779aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
278069b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
278169b46751STobias Grosser     }
2782aef5196fSTobias Grosser 
2783f384594dSTobias Grosser     if (DumpSchedule) {
2784f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2785f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2786f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2787f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2788f384594dSTobias Grosser       if (Schedule)
2789f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2790f384594dSTobias Grosser       else
2791f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2792f384594dSTobias Grosser 
2793f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2794f384594dSTobias Grosser       isl_printer_free(P);
2795f384594dSTobias Grosser     }
2796f384594dSTobias Grosser 
279769b46751STobias Grosser     if (DumpCode) {
279869b46751STobias Grosser       printf("Code\n");
279969b46751STobias Grosser       printf("====\n");
280069b46751STobias Grosser       if (PPCGGen->tree)
280169b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
280269b46751STobias Grosser       else
280369b46751STobias Grosser         printf("No code generated\n");
280469b46751STobias Grosser     }
280569b46751STobias Grosser 
2806f384594dSTobias Grosser     isl_schedule_free(Schedule);
2807f384594dSTobias Grosser 
2808f384594dSTobias Grosser     return PPCGGen;
2809f384594dSTobias Grosser   }
2810f384594dSTobias Grosser 
2811f384594dSTobias Grosser   /// Free gpu_gen structure.
2812f384594dSTobias Grosser   ///
2813f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2814f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2815f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2816f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2817f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2818f384594dSTobias Grosser     free(PPCGGen);
2819f384594dSTobias Grosser   }
2820f384594dSTobias Grosser 
2821b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2822b307ed4dSTobias Grosser   ///
2823b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2824b307ed4dSTobias Grosser   /// ourselves.
2825b307ed4dSTobias Grosser   ///
2826b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2827b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2828b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2829b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2830b307ed4dSTobias Grosser     free(PPCGScop->options);
2831b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2832b307ed4dSTobias Grosser   }
2833b307ed4dSTobias Grosser 
283482f2af35STobias Grosser   /// Approximate the number of points in the set.
283582f2af35STobias Grosser   ///
283682f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
283782f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
283882f2af35STobias Grosser   ///
283982f2af35STobias Grosser   /// @param Set   The set to count.
284082f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
284182f2af35STobias Grosser   ///              expression.
284282f2af35STobias Grosser   ///
284382f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
284482f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
284582f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
284682f2af35STobias Grosser 
284782f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
284882f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
284982f2af35STobias Grosser 
285082f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
285182f2af35STobias Grosser     Space = isl_space_params(Space);
285282f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
285382f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
285482f2af35STobias Grosser 
285582f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
285682f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
285782f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
285882f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
285982f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
286082f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
286182f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
286282f2af35STobias Grosser     }
286382f2af35STobias Grosser 
286482f2af35STobias Grosser     isl_set_free(Set);
286582f2af35STobias Grosser     isl_pw_aff_free(OneAff);
286682f2af35STobias Grosser 
286782f2af35STobias Grosser     return Expr;
286882f2af35STobias Grosser   }
286982f2af35STobias Grosser 
287082f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
287182f2af35STobias Grosser   /// statement.
287282f2af35STobias Grosser   ///
287382f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
287482f2af35STobias Grosser   ///              instructions.
287582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
287682f2af35STobias Grosser   ///              expression.
287782f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
287882f2af35STobias Grosser   ///          by @p Stmt.
287982f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
288082f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
288182f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
288282f2af35STobias Grosser 
288382f2af35STobias Grosser     long InstCount = 0;
288482f2af35STobias Grosser 
288582f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
288682f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
288782f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
288882f2af35STobias Grosser     } else {
288982f2af35STobias Grosser       auto *R = Stmt.getRegion();
289082f2af35STobias Grosser 
289182f2af35STobias Grosser       for (auto *BB : R->blocks()) {
289282f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
289382f2af35STobias Grosser       }
289482f2af35STobias Grosser     }
289582f2af35STobias Grosser 
289682f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
289782f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
289882f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
289982f2af35STobias Grosser   }
290082f2af35STobias Grosser 
290182f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
290282f2af35STobias Grosser   ///
290382f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
290482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
290582f2af35STobias Grosser   ///              expression.
290682f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
290782f2af35STobias Grosser   ///          in @p S.
290882f2af35STobias Grosser   __isl_give isl_ast_expr *
290982f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
291082f2af35STobias Grosser     isl_ast_expr *Instructions;
291182f2af35STobias Grosser 
291282f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
291382f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
291482f2af35STobias Grosser 
291582f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
291682f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
291782f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
291882f2af35STobias Grosser     }
291982f2af35STobias Grosser     return Instructions;
292082f2af35STobias Grosser   }
292182f2af35STobias Grosser 
292282f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
292382f2af35STobias Grosser   ///
292482f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
292582f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
292682f2af35STobias Grosser   ///              expression.
292782f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
292882f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
292982f2af35STobias Grosser   __isl_give isl_ast_expr *
293082f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
293182f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
293282f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
293382f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
293482f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
293582f2af35STobias Grosser   }
293682f2af35STobias Grosser 
2937f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
2938f291c8d5SSiddharth Bhat   /// kernels.
2939f291c8d5SSiddharth Bhat   ///
2940f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
2941f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
2942f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) {
2943f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
2944f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2945f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2946f291c8d5SSiddharth Bhat         continue;
2947f291c8d5SSiddharth Bhat       }
2948f291c8d5SSiddharth Bhat 
2949bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
2950bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2951bccaea57SSiddharth Bhat         if (!p)
2952bccaea57SSiddharth Bhat           continue;
2953bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
2954bccaea57SSiddharth Bhat           return true;
2955bccaea57SSiddharth Bhat       }
2956f291c8d5SSiddharth Bhat     }
2957bccaea57SSiddharth Bhat     return false;
2958bccaea57SSiddharth Bhat   }
2959bccaea57SSiddharth Bhat 
2960f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
2961f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
2962bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
2963bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
2964f291c8d5SSiddharth Bhat         if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock()))
2965bccaea57SSiddharth Bhat           return true;
2966bccaea57SSiddharth Bhat       } else {
2967bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
2968bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
2969bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2970f291c8d5SSiddharth Bhat           if (containsInvalidKernelFunctionInBllock(BB))
2971bccaea57SSiddharth Bhat             return true;
2972bccaea57SSiddharth Bhat       }
2973bccaea57SSiddharth Bhat     }
2974bccaea57SSiddharth Bhat     return false;
2975bccaea57SSiddharth Bhat   }
2976bccaea57SSiddharth Bhat 
297738fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
297838fc0aedSTobias Grosser   ///
297932837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
298032837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
298132837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
298238fc0aedSTobias Grosser     ScopAnnotator Annotator;
298338fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
298438fc0aedSTobias Grosser 
298538fc0aedSTobias Grosser     Region *R = &S->getRegion();
298638fc0aedSTobias Grosser 
298738fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
298838fc0aedSTobias Grosser 
298938fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
299038fc0aedSTobias Grosser 
299138fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
299238fc0aedSTobias Grosser 
299338fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
299438fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
299538fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
299638fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
299738fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
299838fc0aedSTobias Grosser     // code generating this scop.
299903346c27SSiddharth Bhat     BBPair StartExitBlocks;
300003346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
300103346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
30022d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3003256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
300438fc0aedSTobias Grosser 
300503346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
300603346c27SSiddharth Bhat 
30072d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
300817f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3009acf80064SEli Friedman 
301038fc0aedSTobias Grosser     // TODO: Handle LICM
301138fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
301238fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
301338fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3014cb1aef8dSTobias Grosser 
3015cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
30162b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
301782f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
301882f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3019cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3020cb1aef8dSTobias Grosser 
3021*9e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
3022*9e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
3023*9e3db2b7SSiddharth Bhat     NodeBuilder.preloadInvariantLoads();
3024*9e3db2b7SSiddharth Bhat 
3025cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3026cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3027cb1aef8dSTobias Grosser 
302838fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3029fa7b0802STobias Grosser 
303038fc0aedSTobias Grosser     NodeBuilder.create(Root);
30315857b701STobias Grosser 
3032bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3033bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3034de244eb4STobias Grosser     /// point in running it on a GPU.
3035bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
303603346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3037bc653f20STobias Grosser 
30385857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
303903346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
304038fc0aedSTobias Grosser   }
304138fc0aedSTobias Grosser 
3042e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3043e938517eSTobias Grosser     S = &CurrentScop;
304438fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
304538fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
304638fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
30477b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
304838fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3049e938517eSTobias Grosser 
3050f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3051f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3052f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3053bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3054bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
3055f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
3056f291c8d5SSiddharth Bhat       DEBUG(
3057f291c8d5SSiddharth Bhat           dbgs()
3058f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3059f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3060bccaea57SSiddharth Bhat       return false;
3061f291c8d5SSiddharth Bhat     }
3062bccaea57SSiddharth Bhat 
3063e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3064e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3065f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
306638fc0aedSTobias Grosser 
306702ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
306832837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
306902ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
307002ca346eSSingapuram Sanjay Srivallabh     }
307138fc0aedSTobias Grosser 
3072b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3073f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3074e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3075e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3076e938517eSTobias Grosser 
3077e938517eSTobias Grosser     return true;
3078e938517eSTobias Grosser   }
30799dfe4e7cSTobias Grosser 
30809dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
30819dfe4e7cSTobias Grosser 
30829dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
30839dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
30849dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
30859dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
30865cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
30879dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
30889dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
30899dfe4e7cSTobias Grosser 
30909dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
30919dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
30929dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
30939dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
30949dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
30955cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
30969dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
30979dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
30989dfe4e7cSTobias Grosser 
30999dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
31009dfe4e7cSTobias Grosser     //        region tree.
31019dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
31029dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
31039dfe4e7cSTobias Grosser   }
31049dfe4e7cSTobias Grosser };
310524222c73STobias Grosser } // namespace
31069dfe4e7cSTobias Grosser 
31079dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
31089dfe4e7cSTobias Grosser 
310917f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
311017f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
311117f01968SSiddharth Bhat   generator->Runtime = Runtime;
311217f01968SSiddharth Bhat   generator->Architecture = Arch;
311317f01968SSiddharth Bhat   return generator;
311417f01968SSiddharth Bhat }
31159dfe4e7cSTobias Grosser 
31169dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
31179dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
31189dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
31199dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
31209dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
31219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
31229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
31235cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
31249dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
31259dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3126