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 
1409e3db2b7SSiddharth Bhat   /// Tagged must kills stripped of the tags.
1419e3db2b7SSiddharth Bhat   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
1429e3db2b7SSiddharth Bhat   isl::union_map MustKills;
1439e3db2b7SSiddharth Bhat 
1449e3db2b7SSiddharth 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));
1869e3db2b7SSiddharth 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 
2339e3db2b7SSiddharth Bhat     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
2349e3db2b7SSiddharth Bhat     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
2359e3db2b7SSiddharth 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)) {
10159e3db2b7SSiddharth 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++) {
10199e3db2b7SSiddharth 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) {
10599e3db2b7SSiddharth 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   }
11639e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11649e3db2b7SSiddharth Bhat     initializeAfterRTH();
11659e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11669e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11679e3db2b7SSiddharth Bhat     return;
11689e3db2b7SSiddharth Bhat   }
11699e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11709e3db2b7SSiddharth Bhat     finalize();
11719e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11729e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11739e3db2b7SSiddharth Bhat     return;
11749e3db2b7SSiddharth 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
130754491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
130854491db6STobias Grosser   // "llvm.copysign".
130954491db6STobias Grosser   const StringRef Name = F->getName();
131054491db6STobias Grosser   return F->isIntrinsic() &&
131154491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
131254491db6STobias Grosser           Name.startswith("llvm.copysign"));
1313f291c8d5SSiddharth Bhat }
1314f291c8d5SSiddharth Bhat 
1315f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1316f291c8d5SSiddharth Bhat ///
1317f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1318f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1319f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1320f291c8d5SSiddharth Bhat /// `Function`s.
1321f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1322f291c8d5SSiddharth Bhat 
1323f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1324f291c8d5SSiddharth Bhat static SetVector<Function *>
1325f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1326f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1327f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1328f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1329f291c8d5SSiddharth Bhat     if (F) {
1330f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1331f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1332f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1333f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1334f291c8d5SSiddharth Bhat     }
1335f291c8d5SSiddharth Bhat   }
1336f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1337f291c8d5SSiddharth Bhat }
1338f291c8d5SSiddharth Bhat 
1339f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1340f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1341edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1342edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1343edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1344edb885cbSTobias Grosser   SubtreeReferences References = {
1345edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1346edb885cbSTobias Grosser 
1347edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1348edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1349edb885cbSTobias Grosser 
1350edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1351edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1352edb885cbSTobias Grosser 
1353edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1354edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1355edb885cbSTobias Grosser 
1356edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1357d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1358edb885cbSTobias Grosser 
1359edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1360edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1361edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1362edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1363edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1364edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1365edb885cbSTobias Grosser     isl_id_free(Id);
1366edb885cbSTobias Grosser   }
1367edb885cbSTobias Grosser   isl_space_free(Space);
1368edb885cbSTobias Grosser 
1369edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1370edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1371edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1372edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1373edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1374edb885cbSTobias Grosser     isl_id_free(Id);
1375edb885cbSTobias Grosser   }
1376edb885cbSTobias Grosser 
1377f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1378f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1379f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1380f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1381f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1382f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1383f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1384f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1385f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1386f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1387f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1388f291c8d5SSiddharth Bhat 
1389a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1390a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1391a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1392a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1393a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1394a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1395a1b2086aSSiddharth Bhat     else
1396a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1397a1b2086aSSiddharth Bhat   }
1398a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1399edb885cbSTobias Grosser }
1400edb885cbSTobias Grosser 
140174dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
140274dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
140374dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
140474dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
140574dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
140674dc3cb4STobias Grosser 
140774dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
140874dc3cb4STobias Grosser     DT.eraseNode(BB);
140974dc3cb4STobias Grosser }
141074dc3cb4STobias Grosser 
141174dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
141274dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
141374dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
141474dc3cb4STobias Grosser     if (L)
141574dc3cb4STobias Grosser       SE.forgetLoop(L);
141674dc3cb4STobias Grosser   }
141774dc3cb4STobias Grosser }
141874dc3cb4STobias Grosser 
141974dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
142074dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
142174dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
142274dc3cb4STobias Grosser     if (L)
142374dc3cb4STobias Grosser       SE.forgetLoop(L);
142474dc3cb4STobias Grosser     LI.removeBlock(&BB);
142574dc3cb4STobias Grosser   }
142674dc3cb4STobias Grosser }
142774dc3cb4STobias Grosser 
142879a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
142979a947c2STobias Grosser   std::vector<Value *> Sizes;
143079a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
143179a947c2STobias Grosser 
143279a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
143379a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
143479a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
143579a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
143679a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
143779a947c2STobias Grosser     Sizes.push_back(Res);
143879a947c2STobias Grosser   }
143979a947c2STobias Grosser   isl_ast_build_free(Context);
144079a947c2STobias Grosser 
144179a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
144279a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
144379a947c2STobias Grosser 
144479a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
144579a947c2STobias Grosser }
144679a947c2STobias Grosser 
144779a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
144879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
144979a947c2STobias Grosser   std::vector<Value *> Sizes;
145079a947c2STobias Grosser 
145179a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
145279a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
145379a947c2STobias Grosser     Sizes.push_back(Res);
145479a947c2STobias Grosser   }
145579a947c2STobias Grosser 
145679a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
145779a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
145879a947c2STobias Grosser 
145979a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
146079a947c2STobias Grosser }
146179a947c2STobias Grosser 
1462a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1463a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1464a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1465a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1466a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1467a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1468a90be207SSiddharth Bhat }
1469a90be207SSiddharth Bhat 
147057693272STobias Grosser Value *
147157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
147257693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1473a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1474a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1475a90be207SSiddharth Bhat 
1476a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
147779a947c2STobias Grosser 
147879a947c2STobias Grosser   BasicBlock *EntryBlock =
147979a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
148067726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
148179a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
148267726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
148367726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
148479a947c2STobias Grosser 
148579a947c2STobias Grosser   int Index = 0;
148679a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
148779a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
148879a947c2STobias Grosser       continue;
148979a947c2STobias Grosser 
149079a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
149179a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
149279a947c2STobias Grosser 
1493a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1494a90be207SSiddharth Bhat 
1495abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1496abed4969SSiddharth Bhat     if (ManagedMemory) {
1497abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1498abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1499abed4969SSiddharth Bhat     } else {
1500abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
150179a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1502abed4969SSiddharth Bhat     }
1503abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1504abed4969SSiddharth Bhat                                   "initialized");
1505aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1506aaabbbf8STobias Grosser 
1507aaabbbf8STobias Grosser     if (Offset) {
1508aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1509aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1510aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1511aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1512aaabbbf8STobias Grosser     }
1513fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1514fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1515aaabbbf8STobias Grosser 
1516fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1517abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1518abed4969SSiddharth Bhat       if (ManagedMemory)
1519abed4969SSiddharth Bhat         ValPtr = DevArray;
1520abed4969SSiddharth Bhat       else
1521abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1522abed4969SSiddharth Bhat 
1523abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1524abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1525fe74a7a1STobias Grosser       Value *ValPtrCast =
1526fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1527fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1528fe74a7a1STobias Grosser     } else {
152967726b32STobias Grosser       Instruction *Param =
153067726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
153167726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
153279a947c2STobias Grosser                          EntryBlock->getTerminator());
153379a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
153479a947c2STobias Grosser       Value *ParamTyped =
153579a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
153679a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1537fe74a7a1STobias Grosser     }
153879a947c2STobias Grosser     Index++;
153979a947c2STobias Grosser   }
154079a947c2STobias Grosser 
1541a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1542a490147cSTobias Grosser 
1543a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1544a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1545a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1546a490147cSTobias Grosser     isl_id_free(Id);
1547a90be207SSiddharth Bhat 
1548a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1549a90be207SSiddharth Bhat 
155067726b32STobias Grosser     Instruction *Param =
155167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
155267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1553a490147cSTobias Grosser                        EntryBlock->getTerminator());
1554a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1555a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1556a490147cSTobias Grosser     Index++;
1557a490147cSTobias Grosser   }
1558a490147cSTobias Grosser 
1559d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1560d8b94bcaSTobias Grosser 
1561d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1562d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1563d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1564a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1565a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1566d8b94bcaSTobias Grosser     isl_id_free(Id);
1567a90be207SSiddharth Bhat 
1568a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1569a90be207SSiddharth Bhat 
157067726b32STobias Grosser     Instruction *Param =
157167726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
157267726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1573d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1574d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1575a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1576d8b94bcaSTobias Grosser     Index++;
1577d8b94bcaSTobias Grosser   }
1578d8b94bcaSTobias Grosser 
157957693272STobias Grosser   for (auto Val : SubtreeValues) {
1580a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1581a90be207SSiddharth Bhat 
158267726b32STobias Grosser     Instruction *Param =
158367726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
158467726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
158557693272STobias Grosser                        EntryBlock->getTerminator());
158657693272STobias Grosser     Builder.CreateStore(Val, Param);
1587a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1588a90be207SSiddharth Bhat     Index++;
1589a90be207SSiddharth Bhat   }
1590a90be207SSiddharth Bhat 
1591a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1592a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1593a90be207SSiddharth Bhat     Instruction *Param =
1594a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1595a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1596a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1597a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1598a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
159957693272STobias Grosser     Index++;
160057693272STobias Grosser   }
160157693272STobias Grosser 
160279a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
160379a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
160479a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
160579a947c2STobias Grosser }
160679a947c2STobias Grosser 
1607f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1608f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1609f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1610f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1611f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1612f291c8d5SSiddharth Bhat     if (!Clone)
1613f291c8d5SSiddharth Bhat       Clone =
1614f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1615f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1616f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1617f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1618f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1619f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1620f291c8d5SSiddharth Bhat   }
1621f291c8d5SSiddharth Bhat }
162232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
162332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
162432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
162532837fe3STobias Grosser   isl_id_free(Id);
162632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
162732837fe3STobias Grosser 
1628bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1629bc653f20STobias Grosser     DeepestParallel =
1630bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1631bc653f20STobias Grosser   else
1632bc653f20STobias Grosser     DeepestSequential =
1633bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1634bc653f20STobias Grosser 
1635c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1636c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1637c1c6a2a6STobias Grosser 
1638f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1639f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1640f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1641edb885cbSTobias Grosser 
164232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
164332837fe3STobias Grosser 
164432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1645472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1646edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1647587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1648b06ff457STobias Grosser   ScalarMap.clear();
164932837fe3STobias Grosser 
1650edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1651edb885cbSTobias Grosser 
1652edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1653edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1654edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1655edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1656edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1657edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1658edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1659edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1660edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1661edb885cbSTobias Grosser     SubtreeValues.insert(V);
1662edb885cbSTobias Grosser   }
1663edb885cbSTobias Grosser 
1664f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1665f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
166632837fe3STobias Grosser 
166759ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
166859ab0705STobias Grosser 
166951dfc275STobias Grosser   finalizeKernelArguments(Kernel);
167074dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1671c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
167274dc3cb4STobias Grosser   clearDominators(F);
167374dc3cb4STobias Grosser   clearScalarEvolution(F);
167474dc3cb4STobias Grosser   clearLoops(F);
167574dc3cb4STobias Grosser 
1676472f9654STobias Grosser   IDToValue = HostIDs;
167732837fe3STobias Grosser 
1678b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1679b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1680edb885cbSTobias Grosser   EscapeMap.clear();
1681edb885cbSTobias Grosser   IDToSAI.clear();
168274dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
168374dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
16844d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
168574dc3cb4STobias Grosser   LocalArrays.clear();
1686edb885cbSTobias Grosser 
168751dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
168851dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
168957693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
169079a947c2STobias Grosser 
169179f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
169257793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
169357793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
169457793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
169579a947c2STobias Grosser 
169679a947c2STobias Grosser   Value *GridDimX, *GridDimY;
169779a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
169879a947c2STobias Grosser 
169979a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
170079a947c2STobias Grosser                          BlockDimZ, Parameters);
170157793596STobias Grosser   createCallFreeKernel(GPUKernel);
1702b513b491STobias Grosser 
1703b513b491STobias Grosser   for (auto Id : KernelIds)
1704b513b491STobias Grosser     isl_id_free(Id);
1705b513b491STobias Grosser 
1706b513b491STobias Grosser   KernelIds.clear();
170732837fe3STobias Grosser }
170832837fe3STobias Grosser 
170932837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
171032837fe3STobias Grosser ///
171132837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
171232837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1713d277fedaSSiddharth Bhat   std::string Ret = "";
171432837fe3STobias Grosser 
1715d277fedaSSiddharth Bhat   if (!is64Bit) {
1716d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-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   } else {
1720d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1721d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1722d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1723d277fedaSSiddharth Bhat   }
172432837fe3STobias Grosser 
172532837fe3STobias Grosser   return Ret;
172632837fe3STobias Grosser }
172732837fe3STobias Grosser 
1728edb885cbSTobias Grosser Function *
1729edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1730edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
173132837fe3STobias Grosser   std::vector<Type *> Args;
173279f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
173332837fe3STobias Grosser 
173432837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
173532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
173632837fe3STobias Grosser       continue;
173732837fe3STobias Grosser 
1738fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1739fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1740fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1741fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1742fe74a7a1STobias Grosser     } else {
1743d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1744d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
174532837fe3STobias Grosser     }
1746fe74a7a1STobias Grosser   }
174732837fe3STobias Grosser 
1748f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1749f6044bd0STobias Grosser 
1750f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1751f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1752f6044bd0STobias Grosser 
1753c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1754c84a1995STobias Grosser 
1755cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1756cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1757cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1758cf66ef26STobias Grosser     isl_id_free(Id);
1759cf66ef26STobias Grosser     Args.push_back(Val->getType());
1760cf66ef26STobias Grosser   }
1761c84a1995STobias Grosser 
1762edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1763edb885cbSTobias Grosser     Args.push_back(V->getType());
1764edb885cbSTobias Grosser 
176532837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
176632837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
176732837fe3STobias Grosser                               GPUModule.get());
176817f01968SSiddharth Bhat 
176917f01968SSiddharth Bhat   switch (Arch) {
177017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
177132837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
177217f01968SSiddharth Bhat     break;
177317f01968SSiddharth Bhat   }
177432837fe3STobias Grosser 
177532837fe3STobias Grosser   auto Arg = FN->arg_begin();
177632837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
177732837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
177832837fe3STobias Grosser       continue;
177932837fe3STobias Grosser 
1780edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1781edb885cbSTobias Grosser 
1782edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1783edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1784edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1785edb885cbSTobias Grosser     Value *Val = &*Arg;
1786edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1787edb885cbSTobias Grosser     isl_ast_build *Build =
1788edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1789f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1790edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1791edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
17929e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1793edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1794edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1795edb885cbSTobias Grosser     }
1796edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
17974d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
179874dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1799edb885cbSTobias Grosser 
1800edb885cbSTobias Grosser     isl_ast_build_free(Build);
1801b513b491STobias Grosser     KernelIds.push_back(Id);
1802edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
180332837fe3STobias Grosser     Arg++;
180432837fe3STobias Grosser   }
180532837fe3STobias Grosser 
1806f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1807f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1808f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1809f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1810f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1811f6044bd0STobias Grosser     Arg++;
1812f6044bd0STobias Grosser   }
1813f6044bd0STobias Grosser 
1814c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1815c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1816c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
181712453403STobias Grosser     Value *Val = IDToValue[Id];
181812453403STobias Grosser     ValueMap[Val] = &*Arg;
1819c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1820c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1821c84a1995STobias Grosser     Arg++;
1822c84a1995STobias Grosser   }
1823c84a1995STobias Grosser 
1824edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1825edb885cbSTobias Grosser     Arg->setName(V->getName());
1826edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1827edb885cbSTobias Grosser     Arg++;
1828edb885cbSTobias Grosser   }
1829edb885cbSTobias Grosser 
183032837fe3STobias Grosser   return FN;
183132837fe3STobias Grosser }
183232837fe3STobias Grosser 
1833472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
183417f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
183517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1836472f9654STobias Grosser 
183717f01968SSiddharth Bhat   switch (Arch) {
183817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
183917f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
184017f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
184117f01968SSiddharth Bhat 
184217f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
184317f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
184417f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
184517f01968SSiddharth Bhat     break;
184617f01968SSiddharth Bhat   }
1847472f9654STobias Grosser 
1848472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1849472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1850472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1851472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1852472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1853472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1854472f9654STobias Grosser     IDToValue[Id] = Val;
1855472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1856472f9654STobias Grosser   };
1857472f9654STobias Grosser 
1858472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1859472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1860472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1861472f9654STobias Grosser   }
1862472f9654STobias Grosser 
1863472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1864472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1865472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1866472f9654STobias Grosser   }
1867472f9654STobias Grosser }
1868472f9654STobias Grosser 
186900bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
187000bb5a99STobias Grosser   auto Arg = FN->arg_begin();
187100bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
187200bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
187300bb5a99STobias Grosser       continue;
187400bb5a99STobias Grosser 
187500bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
187600bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
187700bb5a99STobias Grosser     isl_id_free(Id);
187800bb5a99STobias Grosser 
187900bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
188000bb5a99STobias Grosser       Arg++;
188100bb5a99STobias Grosser       continue;
188200bb5a99STobias Grosser     }
188300bb5a99STobias Grosser 
1884fe74a7a1STobias Grosser     Value *Val = &*Arg;
1885fe74a7a1STobias Grosser 
1886fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
188700bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1888fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1889fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1890fe74a7a1STobias Grosser     }
1891fe74a7a1STobias Grosser 
1892fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
189300bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
189400bb5a99STobias Grosser 
189500bb5a99STobias Grosser     Arg++;
189600bb5a99STobias Grosser   }
189700bb5a99STobias Grosser }
189800bb5a99STobias Grosser 
189951dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
190051dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
190151dfc275STobias Grosser   auto Arg = FN->arg_begin();
190251dfc275STobias Grosser 
190351dfc275STobias Grosser   bool StoredScalar = false;
190451dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
190551dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
190651dfc275STobias Grosser       continue;
190751dfc275STobias Grosser 
190851dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
190951dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
191051dfc275STobias Grosser     isl_id_free(Id);
191151dfc275STobias Grosser 
191251dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
191351dfc275STobias Grosser       Arg++;
191451dfc275STobias Grosser       continue;
191551dfc275STobias Grosser     }
191651dfc275STobias Grosser 
191751dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
191851dfc275STobias Grosser       Arg++;
191951dfc275STobias Grosser       continue;
192051dfc275STobias Grosser     }
192151dfc275STobias Grosser 
192251dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
192351dfc275STobias Grosser     Value *ArgPtr = &*Arg;
192451dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
192551dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
192651dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
192751dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
192851dfc275STobias Grosser     StoredScalar = true;
192951dfc275STobias Grosser 
193051dfc275STobias Grosser     Arg++;
193151dfc275STobias Grosser   }
193251dfc275STobias Grosser 
193351dfc275STobias Grosser   if (StoredScalar)
193451dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
193551dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
193651dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
193751dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
193851dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
193951dfc275STobias Grosser       BuildSuccessful = 0;
194051dfc275STobias Grosser }
194151dfc275STobias Grosser 
1942b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1943b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1944b513b491STobias Grosser 
1945b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1946b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1947b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1948b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1949b513b491STobias Grosser 
1950f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1951b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1952b513b491STobias Grosser 
1953f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1954928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1955b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1956f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1957b513b491STobias Grosser       isl_val_free(Val);
1958b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1959928d7573STobias Grosser     }
1960928d7573STobias Grosser 
1961928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1962928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1963928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1964928d7573STobias Grosser       isl_val_free(Val);
1965b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1966b513b491STobias Grosser     }
1967b513b491STobias Grosser 
1968130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1969130ca30fSTobias Grosser     Value *Allocation;
1970130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1971130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1972130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1973130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1974130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1975f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1976f919d8b3STobias Grosser 
1977130ca30fSTobias Grosser       Allocation = GlobalVar;
1978130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1979130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1980130ca30fSTobias Grosser     } else {
1981130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1982130ca30fSTobias Grosser     }
19834d5a9172STobias Grosser     SAI =
19844d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1985b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1986130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1987130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1988b513b491STobias Grosser     KernelIds.push_back(Id);
1989b513b491STobias Grosser     IDToSAI[Id] = SAI;
1990b513b491STobias Grosser   }
1991b513b491STobias Grosser }
1992b513b491STobias Grosser 
1993f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
1994f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1995f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
199679f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
199732837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
199817f01968SSiddharth Bhat 
199917f01968SSiddharth Bhat   switch (Arch) {
200017f01968SSiddharth Bhat   case GPUArch::NVPTX64:
200117f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
200232837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
200317f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
200417f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
200532837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
200617f01968SSiddharth Bhat     break;
200717f01968SSiddharth Bhat   }
200832837fe3STobias Grosser 
2009edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
201032837fe3STobias Grosser 
201159ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
201232837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
201332837fe3STobias Grosser 
201459ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
201559ab0705STobias Grosser 
201632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
201732837fe3STobias Grosser   Builder.CreateRetVoid();
201832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2019472f9654STobias Grosser 
2020629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2021629109b6STobias Grosser 
202200bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2023b513b491STobias Grosser   createKernelVariables(Kernel, FN);
2024472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
202532837fe3STobias Grosser }
202632837fe3STobias Grosser 
202774dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
202817f01968SSiddharth Bhat   llvm::Triple GPUTriple;
202917f01968SSiddharth Bhat 
203017f01968SSiddharth Bhat   switch (Arch) {
203117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
203217f01968SSiddharth Bhat     switch (Runtime) {
203317f01968SSiddharth Bhat     case GPURuntime::CUDA:
203417f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
203517f01968SSiddharth Bhat       break;
203617f01968SSiddharth Bhat     case GPURuntime::OpenCL:
203717f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
203817f01968SSiddharth Bhat       break;
203917f01968SSiddharth Bhat     }
204017f01968SSiddharth Bhat     break;
204117f01968SSiddharth Bhat   }
204217f01968SSiddharth Bhat 
204374dc3cb4STobias Grosser   std::string ErrMsg;
204474dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
204574dc3cb4STobias Grosser 
204674dc3cb4STobias Grosser   if (!GPUTarget) {
204774dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
204874dc3cb4STobias Grosser     return "";
204974dc3cb4STobias Grosser   }
205074dc3cb4STobias Grosser 
205174dc3cb4STobias Grosser   TargetOptions Options;
205274dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
205317f01968SSiddharth Bhat 
205417f01968SSiddharth Bhat   std::string subtarget;
205517f01968SSiddharth Bhat 
205617f01968SSiddharth Bhat   switch (Arch) {
205717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
205817f01968SSiddharth Bhat     subtarget = CudaVersion;
205917f01968SSiddharth Bhat     break;
206017f01968SSiddharth Bhat   }
206117f01968SSiddharth Bhat 
206217f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
206317f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
206474dc3cb4STobias Grosser 
206574dc3cb4STobias Grosser   SmallString<0> ASMString;
206674dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
206774dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
206874dc3cb4STobias Grosser 
206974dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
207074dc3cb4STobias Grosser 
207174dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
207274dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
207374dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
207474dc3cb4STobias Grosser     return "";
207574dc3cb4STobias Grosser   }
207674dc3cb4STobias Grosser 
207774dc3cb4STobias Grosser   PM.run(*GPUModule);
207874dc3cb4STobias Grosser 
207974dc3cb4STobias Grosser   return ASMStream.str();
208074dc3cb4STobias Grosser }
208174dc3cb4STobias Grosser 
208257793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
208365d7f72fSSiddharth Bhat 
20845857b701STobias Grosser   if (verifyModule(*GPUModule)) {
208565d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
208665d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
208765d7f72fSSiddharth Bhat 
208865d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
208965d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
209065d7f72fSSiddharth Bhat 
20915857b701STobias Grosser     BuildSuccessful = false;
20925857b701STobias Grosser     return "";
20935857b701STobias Grosser   }
209432837fe3STobias Grosser 
209532837fe3STobias Grosser   if (DumpKernelIR)
209632837fe3STobias Grosser     outs() << *GPUModule << "\n";
209732837fe3STobias Grosser 
20989a18d559STobias Grosser   // Optimize module.
20999a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
21009a18d559STobias Grosser   PassManagerBuilder PassBuilder;
21019a18d559STobias Grosser   PassBuilder.OptLevel = 3;
21029a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
21039a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
21049a18d559STobias Grosser   OptPasses.run(*GPUModule);
21059a18d559STobias Grosser 
210674dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
210774dc3cb4STobias Grosser 
210874dc3cb4STobias Grosser   if (DumpKernelASM)
210974dc3cb4STobias Grosser     outs() << Assembly << "\n";
211074dc3cb4STobias Grosser 
211132837fe3STobias Grosser   GPUModule.release();
2112472f9654STobias Grosser   KernelIDs.clear();
211357793596STobias Grosser 
211457793596STobias Grosser   return Assembly;
211532837fe3STobias Grosser }
211632837fe3STobias Grosser 
21179dfe4e7cSTobias Grosser namespace {
21189dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
21199dfe4e7cSTobias Grosser public:
21209dfe4e7cSTobias Grosser   static char ID;
21219dfe4e7cSTobias Grosser 
212217f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
212317f01968SSiddharth Bhat 
212417f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
212517f01968SSiddharth Bhat 
2126e938517eSTobias Grosser   /// The scop that is currently processed.
2127e938517eSTobias Grosser   Scop *S;
2128e938517eSTobias Grosser 
212938fc0aedSTobias Grosser   LoopInfo *LI;
213038fc0aedSTobias Grosser   DominatorTree *DT;
213138fc0aedSTobias Grosser   ScalarEvolution *SE;
213238fc0aedSTobias Grosser   const DataLayout *DL;
213338fc0aedSTobias Grosser   RegionInfo *RI;
213438fc0aedSTobias Grosser 
21359dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
21369dfe4e7cSTobias Grosser 
2137e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2138e938517eSTobias Grosser   ///
2139e938517eSTobias Grosser   /// @returns The compilation options.
2140e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2141e938517eSTobias Grosser     auto DebugOptions =
2142e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2143e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2144e938517eSTobias Grosser 
2145e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2146e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2147e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2148e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
21498950ceadSTobias Grosser     DebugOptions->verbose = false;
2150e938517eSTobias Grosser 
2151e938517eSTobias Grosser     Options->debug = DebugOptions;
2152e938517eSTobias Grosser 
21539e3db2b7SSiddharth Bhat     Options->group_chains = false;
2154e938517eSTobias Grosser     Options->reschedule = true;
2155e938517eSTobias Grosser     Options->scale_tile_loops = false;
2156e938517eSTobias Grosser     Options->wrap = false;
2157e938517eSTobias Grosser 
2158e938517eSTobias Grosser     Options->non_negative_parameters = false;
2159e938517eSTobias Grosser     Options->ctx = nullptr;
2160e938517eSTobias Grosser     Options->sizes = nullptr;
2161e938517eSTobias Grosser 
21629e3db2b7SSiddharth Bhat     Options->tile = true;
21634eaedde5STobias Grosser     Options->tile_size = 32;
21644eaedde5STobias Grosser 
21659e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
21669e3db2b7SSiddharth Bhat 
2167130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2168b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2169b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2170e938517eSTobias Grosser 
2171e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2172e938517eSTobias Grosser     Options->openmp = false;
2173e938517eSTobias Grosser     Options->linearize_device_arrays = true;
21749e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2175e938517eSTobias Grosser 
21769e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
21779e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
21789e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
21799e3db2b7SSiddharth Bhat 
21809e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
21819e3db2b7SSiddharth Bhat     Options->hybrid = false;
2182e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2183e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2184e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2185e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2186e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2187e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2188e938517eSTobias Grosser 
2189e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2190e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2191e938517eSTobias Grosser 
2192e938517eSTobias Grosser     return Options;
2193e938517eSTobias Grosser   }
2194e938517eSTobias Grosser 
2195f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2196f384594dSTobias Grosser   ///
2197f384594dSTobias Grosser   /// Instead of a normal access of the form:
2198f384594dSTobias Grosser   ///
2199f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2200f384594dSTobias Grosser   ///
2201f384594dSTobias Grosser   /// a tagged access has the form
2202f384594dSTobias Grosser   ///
2203f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2204f384594dSTobias Grosser   ///
2205f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2206f384594dSTobias Grosser   /// triggered the access.
2207f384594dSTobias Grosser   ///
2208f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2209f384594dSTobias Grosser   ///
2210f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2211f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2212f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2213f384594dSTobias Grosser 
2214f384594dSTobias Grosser     for (auto &Stmt : *S)
2215f384594dSTobias Grosser       for (auto &Acc : Stmt)
2216f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
2217f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
2218f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2219f384594dSTobias Grosser 
2220f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2221f384594dSTobias Grosser           Space = isl_space_range(Space);
2222f384594dSTobias Grosser           Space = isl_space_from_range(Space);
22236293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2224f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2225f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2226f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2227f384594dSTobias Grosser         }
2228f384594dSTobias Grosser 
2229f384594dSTobias Grosser     return Accesses;
2230f384594dSTobias Grosser   }
2231f384594dSTobias Grosser 
2232f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2233f384594dSTobias Grosser   ///
2234f384594dSTobias Grosser   /// @see getTaggedAccesses
2235f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2236f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2237f384594dSTobias Grosser   }
2238f384594dSTobias Grosser 
2239f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2240f384594dSTobias Grosser   ///
2241f384594dSTobias Grosser   /// @see getTaggedAccesses
2242f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2243f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2244f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2245f384594dSTobias Grosser   }
2246f384594dSTobias Grosser 
2247f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2248f384594dSTobias Grosser   ///
2249f384594dSTobias Grosser   /// @see getTaggedAccesses
2250f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2251f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2252f384594dSTobias Grosser   }
2253f384594dSTobias Grosser 
2254aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2255aef5196fSTobias Grosser   ///
2256aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2257aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2258aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2259aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2260aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2261aef5196fSTobias Grosser   /// the data format that ppcg expects.
2262aef5196fSTobias Grosser   ///
2263aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2264aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2265aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2266bd81a7eeSTobias Grosser         S->getIslCtx(),
2267bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2268aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2269aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
2270aef5196fSTobias Grosser 
2271aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2272aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2273aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2274aef5196fSTobias Grosser     }
2275aef5196fSTobias Grosser 
2276aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
2277d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
2278aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2279aef5196fSTobias Grosser     }
2280aef5196fSTobias Grosser 
2281aef5196fSTobias Grosser     isl_space_free(Space);
2282aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2283aef5196fSTobias Grosser 
2284aef5196fSTobias Grosser     return Names;
2285aef5196fSTobias Grosser   }
2286aef5196fSTobias Grosser 
2287e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2288e938517eSTobias Grosser   ///
2289f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2290f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2291f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2292f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2293e938517eSTobias Grosser   ///
2294e938517eSTobias Grosser   /// @returns A new ppcg scop.
2295e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
22969e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
22979e3db2b7SSiddharth Bhat 
2298e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2299e938517eSTobias Grosser 
2300e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2301a82f2d26SSiddharth Bhat     // enable live range reordering
2302a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2303e938517eSTobias Grosser 
2304e938517eSTobias Grosser     PPCGScop->start = 0;
2305e938517eSTobias Grosser     PPCGScop->end = 0;
2306e938517eSTobias Grosser 
2307f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2308f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
23099e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
23109e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2311f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2312f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2313e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2314f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2315f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2316f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2317f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2318e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
23199e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
23209e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
23219e3db2b7SSiddharth Bhat 
2322e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2323a82f2d26SSiddharth Bhat     PPCGScop->independence =
2324a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2325e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2326e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2327e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2328e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2329e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2330e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2331e938517eSTobias Grosser 
2332f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2333a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2334a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2335a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2336a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2337a82f2d26SSiddharth Bhat 
2338a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2339e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2340e938517eSTobias Grosser 
2341f384594dSTobias Grosser     compute_tagger(PPCGScop);
2342f384594dSTobias Grosser     compute_dependences(PPCGScop);
23439e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2344f384594dSTobias Grosser 
2345e938517eSTobias Grosser     return PPCGScop;
2346e938517eSTobias Grosser   }
2347e938517eSTobias Grosser 
2348a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
234960f63b49STobias Grosser   ///
235060f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
235160f63b49STobias Grosser   ///
235260f63b49STobias Grosser   /// @returns A list of array accesses.
235360f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
235460f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
235560f63b49STobias Grosser 
235660f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
235760f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
235860f63b49STobias Grosser       Access->read = Acc->isRead();
235960f63b49STobias Grosser       Access->write = Acc->isWrite();
236060f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
236160f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
236260f63b49STobias Grosser       Space = isl_space_range(Space);
236360f63b49STobias Grosser       Space = isl_space_from_range(Space);
23646293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
236560f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
236660f63b49STobias Grosser       Access->tagged_access =
236760f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2368b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
236960f63b49STobias Grosser       Access->ref_id = Acc->getId();
237060f63b49STobias Grosser       Access->next = Accesses;
2371b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
237260f63b49STobias Grosser       Accesses = Access;
237360f63b49STobias Grosser     }
237460f63b49STobias Grosser 
237560f63b49STobias Grosser     return Accesses;
237660f63b49STobias Grosser   }
237760f63b49STobias Grosser 
237869b46751STobias Grosser   /// Collect the list of GPU statements.
237969b46751STobias Grosser   ///
238069b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
238169b46751STobias Grosser   /// as well as a list with all memory accesses.
238269b46751STobias Grosser   ///
238369b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
238469b46751STobias Grosser   ///
238569b46751STobias Grosser   /// @returns A linked-list of statements.
238669b46751STobias Grosser   gpu_stmt *getStatements() {
238769b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
238869b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
238969b46751STobias Grosser 
239069b46751STobias Grosser     int i = 0;
239169b46751STobias Grosser     for (auto &Stmt : *S) {
239269b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
239369b46751STobias Grosser 
239469b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
239569b46751STobias Grosser 
239669b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
239769b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
239860f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
239969b46751STobias Grosser       i++;
240069b46751STobias Grosser     }
240169b46751STobias Grosser 
240269b46751STobias Grosser     return Stmts;
240369b46751STobias Grosser   }
240469b46751STobias Grosser 
240560f63b49STobias Grosser   /// Derive the extent of an array.
240660f63b49STobias Grosser   ///
2407d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2408d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2409d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2410d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2411d58acf86STobias Grosser   /// subscript value for the first dimension.
241260f63b49STobias Grosser   ///
241360f63b49STobias Grosser   /// @param Array The array to derive the extent for.
241460f63b49STobias Grosser   ///
241560f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
241660f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2417d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
241860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
241960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2420d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
242160f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2422d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2423d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2424d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2425d58acf86STobias Grosser 
2426d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2427d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2428d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2429d58acf86STobias Grosser     }
2430d58acf86STobias Grosser 
2431d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2432d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2433d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2434d58acf86STobias Grosser     }
2435d58acf86STobias Grosser 
243660f63b49STobias Grosser     isl_set *AccessSet =
243760f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
243860f63b49STobias Grosser 
2439d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2440d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2441d58acf86STobias Grosser 
2442d58acf86STobias Grosser     isl_pw_aff *Val =
2443d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2444d58acf86STobias Grosser 
2445d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2446d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2447d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2448d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2449d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2450d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2451d58acf86STobias Grosser     OuterMin =
2452d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2453d58acf86STobias Grosser     OuterMax =
2454d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2455d58acf86STobias Grosser 
2456d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2457d58acf86STobias Grosser 
2458d58acf86STobias Grosser     Extent = isl_set_intersect(
2459d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2460d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2461d58acf86STobias Grosser 
2462d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2463d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2464d58acf86STobias Grosser 
2465b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2466d58acf86STobias Grosser       isl_pw_aff *PwAff =
2467d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2468b7f68b8cSSiddharth Bhat 
2469b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2470b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2471b7f68b8cSSiddharth Bhat       if (!PwAff) {
2472b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2473b7f68b8cSSiddharth Bhat         continue;
2474b7f68b8cSSiddharth Bhat       }
2475b7f68b8cSSiddharth Bhat 
2476d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2477d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2478d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2479d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2480d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2481d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2482d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2483d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2484d58acf86STobias Grosser     }
2485d58acf86STobias Grosser 
2486d58acf86STobias Grosser     return Extent;
248760f63b49STobias Grosser   }
248860f63b49STobias Grosser 
248960f63b49STobias Grosser   /// Derive the bounds of an array.
249060f63b49STobias Grosser   ///
249160f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
249260f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
249360f63b49STobias Grosser   /// ScopArrayInfo.
249460f63b49STobias Grosser   ///
249560f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
249660f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
249760f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
24989e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
24999e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
25009e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
25019e3db2b7SSiddharth Bhat 
25029e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
25039e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
25049e3db2b7SSiddharth Bhat 
250560f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
250602293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
250702293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
250802293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
250902293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
251002293ed7STobias Grosser         isl_set_free(Dom);
25119e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
25129e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
25139e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
25149e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
251502293ed7STobias Grosser       } else {
251660f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
251760f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
251860f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
251960f63b49STobias Grosser         isl_set_free(Dom);
252060f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
252102293ed7STobias Grosser         isl_local_space *LS =
252202293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
252360f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
252460f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
252560f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
252660f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
25279e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
25289e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
25299e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
253060f63b49STobias Grosser       }
253102293ed7STobias Grosser     }
253260f63b49STobias Grosser 
253360f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
253460f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
253560f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
253660f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
253760f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
25389e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
25399e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
25409e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
254160f63b49STobias Grosser     }
25429e3db2b7SSiddharth Bhat 
25439e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
25449e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
25459e3db2b7SSiddharth Bhat 
25469e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
25479e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
25489e3db2b7SSiddharth Bhat 
25499e3db2b7SSiddharth Bhat     PPCGArray.bound =
25509e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
25519e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
255260f63b49STobias Grosser   }
255360f63b49STobias Grosser 
255460f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
255560f63b49STobias Grosser   ///
255660f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
255760f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
255860f63b49STobias Grosser     int i = 0;
2559d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
256060f63b49STobias Grosser       std::string TypeName;
256160f63b49STobias Grosser       raw_string_ostream OS(TypeName);
256260f63b49STobias Grosser 
256360f63b49STobias Grosser       OS << *Array->getElementType();
256460f63b49STobias Grosser       TypeName = OS.str();
256560f63b49STobias Grosser 
256660f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
256760f63b49STobias Grosser 
256860f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
256960f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
257060f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
257160f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
257260f63b49STobias Grosser       PPCGArray.extent = nullptr;
257360f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
257460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
257560f63b49STobias Grosser       PPCGArray.n_ref = 0;
257660f63b49STobias Grosser       PPCGArray.refs = nullptr;
257760f63b49STobias Grosser       PPCGArray.accessed = true;
2578fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2579fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
258060f63b49STobias Grosser       PPCGArray.has_compound_element = false;
258160f63b49STobias Grosser       PPCGArray.local = false;
258260f63b49STobias Grosser       PPCGArray.declare_local = false;
258360f63b49STobias Grosser       PPCGArray.global = false;
258460f63b49STobias Grosser       PPCGArray.linearize = false;
258560f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
258613c78e4dSTobias Grosser       PPCGArray.user = Array;
258760f63b49STobias Grosser 
25889e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
258960f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
25902d010dafSTobias Grosser       i++;
2591b9fc860aSTobias Grosser 
2592b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
259360f63b49STobias Grosser     }
259460f63b49STobias Grosser   }
259560f63b49STobias Grosser 
259660f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
259760f63b49STobias Grosser   ///
259860f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
259960f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
260060f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
260160f63b49STobias Grosser 
2602d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
260360f63b49STobias Grosser       isl_space *Space = Array->getSpace();
260460f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
260560f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
260660f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
260760f63b49STobias Grosser     }
260860f63b49STobias Grosser 
260960f63b49STobias Grosser     return Maps;
261060f63b49STobias Grosser   }
261160f63b49STobias Grosser 
2612e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2613e938517eSTobias Grosser   ///
2614a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2615e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2616e938517eSTobias Grosser 
2617e938517eSTobias Grosser     if (!PPCGScop)
2618e938517eSTobias Grosser       return nullptr;
2619e938517eSTobias Grosser 
2620e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2621e938517eSTobias Grosser 
2622e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2623e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2624aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
262560f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
262660f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
262760f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
262860f63b49STobias Grosser     PPCGProg->tagged_must_kill =
262960f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
263060f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
263160f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
26329e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2633e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2634a82f2d26SSiddharth Bhat 
2635a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2636a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2637a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2638a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2639a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2640a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
264169b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
264269b46751STobias Grosser     PPCGProg->stmts = getStatements();
264360f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
264460f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
264560f63b49STobias Grosser                                        PPCGProg->n_array);
264660f63b49STobias Grosser 
264760f63b49STobias Grosser     createArrays(PPCGProg);
2648e938517eSTobias Grosser 
2649d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2650e938517eSTobias Grosser     return PPCGProg;
2651e938517eSTobias Grosser   }
2652e938517eSTobias Grosser 
265369b46751STobias Grosser   struct PrintGPUUserData {
265469b46751STobias Grosser     struct cuda_info *CudaInfo;
265569b46751STobias Grosser     struct gpu_prog *PPCGProg;
265669b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
265769b46751STobias Grosser   };
265869b46751STobias Grosser 
265969b46751STobias Grosser   /// Print a user statement node in the host code.
266069b46751STobias Grosser   ///
266169b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
266269b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
266369b46751STobias Grosser   /// host ast.
266469b46751STobias Grosser   ///
266569b46751STobias Grosser   /// @param P The printer to print to
266669b46751STobias Grosser   /// @param Options The printing options to use
266769b46751STobias Grosser   /// @param Node The node to print
266869b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
266969b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
267069b46751STobias Grosser   ///
267169b46751STobias Grosser   /// @returns A printer to which the output has been printed.
267269b46751STobias Grosser   static __isl_give isl_printer *
267369b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
267469b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
267569b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
267669b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
267769b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
267869b46751STobias Grosser 
267969b46751STobias Grosser     if (Id) {
268020251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
268120251734STobias Grosser 
268220251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
268320251734STobias Grosser       // otherwise try to call pet functionality that is not available in
268420251734STobias Grosser       // Polly.
268520251734STobias Grosser       if (IsUser) {
268620251734STobias Grosser         P = isl_printer_start_line(P);
268720251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
268820251734STobias Grosser         P = isl_printer_end_line(P);
268920251734STobias Grosser         isl_id_free(Id);
269020251734STobias Grosser         isl_ast_print_options_free(Options);
269120251734STobias Grosser         return P;
269220251734STobias Grosser       }
269320251734STobias Grosser 
269469b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
269569b46751STobias Grosser       isl_id_free(Id);
269669b46751STobias Grosser       Data->Kernels.push_back(Kernel);
269769b46751STobias Grosser     }
269869b46751STobias Grosser 
269969b46751STobias Grosser     return print_host_user(P, Options, Node, User);
270069b46751STobias Grosser   }
270169b46751STobias Grosser 
270269b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
270369b46751STobias Grosser   ///
270469b46751STobias Grosser   /// @param Kernel The kernel to print
270569b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
270669b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
270769b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
270869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
270969b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
271069b46751STobias Grosser     char *String = isl_printer_get_str(P);
271169b46751STobias Grosser     printf("%s\n", String);
271269b46751STobias Grosser     free(String);
271369b46751STobias Grosser     isl_printer_free(P);
271469b46751STobias Grosser   }
271569b46751STobias Grosser 
271669b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
271769b46751STobias Grosser   ///
271869b46751STobias Grosser   /// @param Tree An AST describing GPU code
271969b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
272069b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
272169b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
272269b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
272369b46751STobias Grosser 
272469b46751STobias Grosser     PrintGPUUserData Data;
272569b46751STobias Grosser     Data.PPCGProg = PPCGProg;
272669b46751STobias Grosser 
272769b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
272869b46751STobias Grosser     Options =
272969b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
273069b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
273169b46751STobias Grosser     char *String = isl_printer_get_str(P);
273269b46751STobias Grosser     printf("# host\n");
273369b46751STobias Grosser     printf("%s\n", String);
273469b46751STobias Grosser     free(String);
273569b46751STobias Grosser     isl_printer_free(P);
273669b46751STobias Grosser 
273769b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
273869b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
273969b46751STobias Grosser       printKernel(Kernel);
274069b46751STobias Grosser     }
274169b46751STobias Grosser   }
274269b46751STobias Grosser 
2743f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2744f384594dSTobias Grosser   //
2745f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2746f384594dSTobias Grosser   //
2747f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2748f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2749f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2750f384594dSTobias Grosser   //
2751f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2752f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2753f384594dSTobias Grosser   // strategy directly from this pass.
2754f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2755f384594dSTobias Grosser 
2756f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2757f384594dSTobias Grosser 
2758f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2759f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2760f384594dSTobias Grosser     PPCGGen->print = nullptr;
2761f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
276260c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2763f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2764f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2765f384594dSTobias Grosser     PPCGGen->types.n = 0;
2766f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2767f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2768f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2769f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2770f384594dSTobias Grosser 
2771f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2772f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2773f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
27742341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2775f384594dSTobias Grosser 
2776f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2777f384594dSTobias Grosser 
2778aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2779aef5196fSTobias Grosser 
278069b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2781aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
278269b46751STobias Grosser     } else {
2783aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
278469b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
278569b46751STobias Grosser     }
2786aef5196fSTobias Grosser 
2787f384594dSTobias Grosser     if (DumpSchedule) {
2788f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2789f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2790f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2791f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2792f384594dSTobias Grosser       if (Schedule)
2793f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2794f384594dSTobias Grosser       else
2795f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2796f384594dSTobias Grosser 
2797f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2798f384594dSTobias Grosser       isl_printer_free(P);
2799f384594dSTobias Grosser     }
2800f384594dSTobias Grosser 
280169b46751STobias Grosser     if (DumpCode) {
280269b46751STobias Grosser       printf("Code\n");
280369b46751STobias Grosser       printf("====\n");
280469b46751STobias Grosser       if (PPCGGen->tree)
280569b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
280669b46751STobias Grosser       else
280769b46751STobias Grosser         printf("No code generated\n");
280869b46751STobias Grosser     }
280969b46751STobias Grosser 
2810f384594dSTobias Grosser     isl_schedule_free(Schedule);
2811f384594dSTobias Grosser 
2812f384594dSTobias Grosser     return PPCGGen;
2813f384594dSTobias Grosser   }
2814f384594dSTobias Grosser 
2815f384594dSTobias Grosser   /// Free gpu_gen structure.
2816f384594dSTobias Grosser   ///
2817f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2818f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2819f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2820f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2821f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2822f384594dSTobias Grosser     free(PPCGGen);
2823f384594dSTobias Grosser   }
2824f384594dSTobias Grosser 
2825b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2826b307ed4dSTobias Grosser   ///
2827b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2828b307ed4dSTobias Grosser   /// ourselves.
2829b307ed4dSTobias Grosser   ///
2830b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2831b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2832b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2833b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2834b307ed4dSTobias Grosser     free(PPCGScop->options);
2835b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2836b307ed4dSTobias Grosser   }
2837b307ed4dSTobias Grosser 
283882f2af35STobias Grosser   /// Approximate the number of points in the set.
283982f2af35STobias Grosser   ///
284082f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
284182f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
284282f2af35STobias Grosser   ///
284382f2af35STobias Grosser   /// @param Set   The set to count.
284482f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
284582f2af35STobias Grosser   ///              expression.
284682f2af35STobias Grosser   ///
284782f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
284882f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
284982f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
285082f2af35STobias Grosser 
285182f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
285282f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
285382f2af35STobias Grosser 
285482f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
285582f2af35STobias Grosser     Space = isl_space_params(Space);
285682f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
285782f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
285882f2af35STobias Grosser 
285982f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
286082f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
286182f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
286282f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
286382f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
286482f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
286582f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
286682f2af35STobias Grosser     }
286782f2af35STobias Grosser 
286882f2af35STobias Grosser     isl_set_free(Set);
286982f2af35STobias Grosser     isl_pw_aff_free(OneAff);
287082f2af35STobias Grosser 
287182f2af35STobias Grosser     return Expr;
287282f2af35STobias Grosser   }
287382f2af35STobias Grosser 
287482f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
287582f2af35STobias Grosser   /// statement.
287682f2af35STobias Grosser   ///
287782f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
287882f2af35STobias Grosser   ///              instructions.
287982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
288082f2af35STobias Grosser   ///              expression.
288182f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
288282f2af35STobias Grosser   ///          by @p Stmt.
288382f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
288482f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
288582f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
288682f2af35STobias Grosser 
288782f2af35STobias Grosser     long InstCount = 0;
288882f2af35STobias Grosser 
288982f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
289082f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
289182f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
289282f2af35STobias Grosser     } else {
289382f2af35STobias Grosser       auto *R = Stmt.getRegion();
289482f2af35STobias Grosser 
289582f2af35STobias Grosser       for (auto *BB : R->blocks()) {
289682f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
289782f2af35STobias Grosser       }
289882f2af35STobias Grosser     }
289982f2af35STobias Grosser 
290082f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
290182f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
290282f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
290382f2af35STobias Grosser   }
290482f2af35STobias Grosser 
290582f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
290682f2af35STobias Grosser   ///
290782f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
290882f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
290982f2af35STobias Grosser   ///              expression.
291082f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
291182f2af35STobias Grosser   ///          in @p S.
291282f2af35STobias Grosser   __isl_give isl_ast_expr *
291382f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
291482f2af35STobias Grosser     isl_ast_expr *Instructions;
291582f2af35STobias Grosser 
291682f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
291782f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
291882f2af35STobias Grosser 
291982f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
292082f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
292182f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
292282f2af35STobias Grosser     }
292382f2af35STobias Grosser     return Instructions;
292482f2af35STobias Grosser   }
292582f2af35STobias Grosser 
292682f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
292782f2af35STobias Grosser   ///
292882f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
292982f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
293082f2af35STobias Grosser   ///              expression.
293182f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
293282f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
293382f2af35STobias Grosser   __isl_give isl_ast_expr *
293482f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
293582f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
293682f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
293782f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
293882f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
293982f2af35STobias Grosser   }
294082f2af35STobias Grosser 
2941f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
2942f291c8d5SSiddharth Bhat   /// kernels.
2943f291c8d5SSiddharth Bhat   ///
2944f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
2945f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
2946*018103d3STobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) {
2947f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
2948f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2949f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2950f291c8d5SSiddharth Bhat         continue;
2951f291c8d5SSiddharth Bhat       }
2952f291c8d5SSiddharth Bhat 
2953bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
2954bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2955bccaea57SSiddharth Bhat         if (!p)
2956bccaea57SSiddharth Bhat           continue;
2957bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
2958bccaea57SSiddharth Bhat           return true;
2959bccaea57SSiddharth Bhat       }
2960f291c8d5SSiddharth Bhat     }
2961bccaea57SSiddharth Bhat     return false;
2962bccaea57SSiddharth Bhat   }
2963bccaea57SSiddharth Bhat 
2964f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
2965f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
2966bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
2967bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
2968*018103d3STobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock()))
2969bccaea57SSiddharth Bhat           return true;
2970bccaea57SSiddharth Bhat       } else {
2971bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
2972bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
2973bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2974*018103d3STobias Grosser           if (containsInvalidKernelFunctionInBlock(BB))
2975bccaea57SSiddharth Bhat             return true;
2976bccaea57SSiddharth Bhat       }
2977bccaea57SSiddharth Bhat     }
2978bccaea57SSiddharth Bhat     return false;
2979bccaea57SSiddharth Bhat   }
2980bccaea57SSiddharth Bhat 
298138fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
298238fc0aedSTobias Grosser   ///
298332837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
298432837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
298532837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
298638fc0aedSTobias Grosser     ScopAnnotator Annotator;
298738fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
298838fc0aedSTobias Grosser 
298938fc0aedSTobias Grosser     Region *R = &S->getRegion();
299038fc0aedSTobias Grosser 
299138fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
299238fc0aedSTobias Grosser 
299338fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
299438fc0aedSTobias Grosser 
299538fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
299638fc0aedSTobias Grosser 
299738fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
299838fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
299938fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
300038fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
300138fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
300238fc0aedSTobias Grosser     // code generating this scop.
300303346c27SSiddharth Bhat     BBPair StartExitBlocks;
300403346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
300503346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
30062d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3007256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
300838fc0aedSTobias Grosser 
300903346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
301003346c27SSiddharth Bhat 
30112d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
301217f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3013acf80064SEli Friedman 
301438fc0aedSTobias Grosser     // TODO: Handle LICM
301538fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
301638fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
301738fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3018cb1aef8dSTobias Grosser 
3019cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
30202b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
302182f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
302282f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3023cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3024cb1aef8dSTobias Grosser 
30259e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
30269e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
30279e3db2b7SSiddharth Bhat     NodeBuilder.preloadInvariantLoads();
30289e3db2b7SSiddharth Bhat 
3029cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3030cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3031cb1aef8dSTobias Grosser 
303238fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3033fa7b0802STobias Grosser 
303438fc0aedSTobias Grosser     NodeBuilder.create(Root);
30355857b701STobias Grosser 
3036bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3037bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3038de244eb4STobias Grosser     /// point in running it on a GPU.
3039bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
304003346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3041bc653f20STobias Grosser 
30425857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
304303346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
304438fc0aedSTobias Grosser   }
304538fc0aedSTobias Grosser 
3046e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3047e938517eSTobias Grosser     S = &CurrentScop;
304838fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
304938fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
305038fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
30517b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
305238fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3053e938517eSTobias Grosser 
3054f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3055f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3056f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3057bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3058bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
3059f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
3060f291c8d5SSiddharth Bhat       DEBUG(
3061f291c8d5SSiddharth Bhat           dbgs()
3062f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3063f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3064bccaea57SSiddharth Bhat       return false;
3065f291c8d5SSiddharth Bhat     }
3066bccaea57SSiddharth Bhat 
3067e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3068e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3069f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
307038fc0aedSTobias Grosser 
307102ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
307232837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
307302ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
307402ca346eSSingapuram Sanjay Srivallabh     }
307538fc0aedSTobias Grosser 
3076b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3077f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3078e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3079e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3080e938517eSTobias Grosser 
3081e938517eSTobias Grosser     return true;
3082e938517eSTobias Grosser   }
30839dfe4e7cSTobias Grosser 
30849dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
30859dfe4e7cSTobias Grosser 
30869dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
30879dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
30889dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
30899dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
30905cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
30919dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
30929dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
30939dfe4e7cSTobias Grosser 
30949dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
30959dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
30969dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
30979dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
30989dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
30995cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
31009dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
31019dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
31029dfe4e7cSTobias Grosser 
31039dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
31049dfe4e7cSTobias Grosser     //        region tree.
31059dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
31069dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
31079dfe4e7cSTobias Grosser   }
31089dfe4e7cSTobias Grosser };
310924222c73STobias Grosser } // namespace
31109dfe4e7cSTobias Grosser 
31119dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
31129dfe4e7cSTobias Grosser 
311317f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
311417f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
311517f01968SSiddharth Bhat   generator->Runtime = Runtime;
311617f01968SSiddharth Bhat   generator->Architecture = Arch;
311717f01968SSiddharth Bhat   return generator;
311817f01968SSiddharth Bhat }
31199dfe4e7cSTobias Grosser 
31209dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
31219dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
31229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
31239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
31249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
31259dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
31269dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
31275cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
31289dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
31299dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3130