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)))
18277eef90fSTobias Grosser       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
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(
25835de9009SSiddharth Bhat     void *StmtT, __isl_take isl_ast_build *Build_C,
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 
26735de9009SSiddharth Bhat   if (!Stmt || !Build_C)
268edb885cbSTobias Grosser     return NULL;
269edb885cbSTobias Grosser 
27035de9009SSiddharth Bhat   isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C));
27135de9009SSiddharth Bhat   isl::ctx Ctx = Build.get_ctx();
27235de9009SSiddharth Bhat   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
273edb885cbSTobias Grosser 
274edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
27535de9009SSiddharth Bhat     isl::map AddrFunc = Acc->getAddressFunction();
27635de9009SSiddharth Bhat     AddrFunc = AddrFunc.intersect_domain(isl::manage(Stmt->getDomain()));
27735de9009SSiddharth Bhat 
27835de9009SSiddharth Bhat     isl::id RefId = Acc->getId();
27935de9009SSiddharth Bhat     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
28035de9009SSiddharth Bhat 
28135de9009SSiddharth Bhat     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
28235de9009SSiddharth Bhat     MPA = MPA.coalesce();
28335de9009SSiddharth Bhat     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
28435de9009SSiddharth Bhat 
28535de9009SSiddharth Bhat     isl::ast_expr Access = Build.access_from(MPA);
28635de9009SSiddharth Bhat     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
28735de9009SSiddharth Bhat     RefToExpr = RefToExpr.set(RefId, Access);
288edb885cbSTobias Grosser   }
289edb885cbSTobias Grosser 
29035de9009SSiddharth Bhat   return RefToExpr.release();
29160c60025STobias Grosser }
292f384594dSTobias Grosser 
293a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
294a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
295a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
296a90be207SSiddharth Bhat   if (bytes == 0)
297a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
298a90be207SSiddharth Bhat   return bytes;
299a90be207SSiddharth Bhat }
300a90be207SSiddharth Bhat 
30138fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
30238fc0aedSTobias Grosser ///
30338fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
304a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
30538fc0aedSTobias Grosser /// for generating GPU specific user nodes.
30638fc0aedSTobias Grosser ///
30738fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
30838fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
30938fc0aedSTobias Grosser public:
3102d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
31138fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
312acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
31317f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
3142d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
31517f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
316edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
317edb885cbSTobias Grosser   }
31838fc0aedSTobias Grosser 
319fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
320fa7b0802STobias Grosser   void initializeAfterRTH();
321fa7b0802STobias Grosser 
322fa7b0802STobias Grosser   /// Finalize the generated scop.
323fa7b0802STobias Grosser   virtual void finalize();
324fa7b0802STobias Grosser 
3255857b701STobias Grosser   /// Track if the full build process was successful.
3265857b701STobias Grosser   ///
3275857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3285857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3295857b701STobias Grosser   bool BuildSuccessful = true;
3305857b701STobias Grosser 
331bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
332bc653f20STobias Grosser   unsigned DeepestSequential = 0;
333bc653f20STobias Grosser 
334bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
335bc653f20STobias Grosser   unsigned DeepestParallel = 0;
336bc653f20STobias Grosser 
33779f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
33879f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
33979f13b9aSSingapuram Sanjay Srivallabh 
34038fc0aedSTobias Grosser private:
34174dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
34274dc3cb4STobias Grosser   ///
34374dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
34474dc3cb4STobias Grosser   /// more.
34574dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
34674dc3cb4STobias Grosser 
34713c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
34813c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3497287aeddSTobias Grosser 
350fa7b0802STobias Grosser   /// The current GPU context.
351fa7b0802STobias Grosser   Value *GPUContext;
352fa7b0802STobias Grosser 
353b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
354b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
355b513b491STobias Grosser 
35632837fe3STobias Grosser   /// A module containing GPU code.
35732837fe3STobias Grosser   ///
35832837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
35932837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
36032837fe3STobias Grosser 
36132837fe3STobias Grosser   /// The GPU program we generate code for.
36232837fe3STobias Grosser   gpu_prog *Prog;
36332837fe3STobias Grosser 
36417f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
36517f01968SSiddharth Bhat   GPURuntime Runtime;
36617f01968SSiddharth Bhat 
36717f01968SSiddharth Bhat   /// The GPU Architecture to target.
36817f01968SSiddharth Bhat   GPUArch Arch;
36917f01968SSiddharth Bhat 
370472f9654STobias Grosser   /// Class to free isl_ids.
371472f9654STobias Grosser   class IslIdDeleter {
372472f9654STobias Grosser   public:
373472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
374472f9654STobias Grosser   };
375472f9654STobias Grosser 
376472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
377472f9654STobias Grosser   ///
378472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
379472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
380472f9654STobias Grosser 
381edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
382edb885cbSTobias Grosser 
38338fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
38438fc0aedSTobias Grosser   ///
38538fc0aedSTobias Grosser   /// These AST nodes can be of type:
38638fc0aedSTobias Grosser   ///
38738fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
38838fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
38913c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
3905260c041STobias Grosser   ///   - In-kernel synchronization
3915260c041STobias Grosser   ///   - In-kernel memory copy statement
39238fc0aedSTobias Grosser   ///
3931fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
3941fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
39532837fe3STobias Grosser 
39613c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
39713c78e4dSTobias Grosser 
39813c78e4dSTobias Grosser   /// Create code for a data transfer statement
39913c78e4dSTobias Grosser   ///
40013c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
40113c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
40213c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
40313c78e4dSTobias Grosser                           enum DataDirection Direction);
40413c78e4dSTobias Grosser 
405edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
406edb885cbSTobias Grosser   ///
407edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
408edb885cbSTobias Grosser   ///
409f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
410f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
411f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
412f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
413f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
414f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
415edb885cbSTobias Grosser 
41679a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
41779a947c2STobias Grosser   ///
41879a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
41979a947c2STobias Grosser   ///
42079a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
42179a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
42279a947c2STobias Grosser 
423abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
424abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
425abed4969SSiddharth Bhat   /// host pointers to the device.
426abed4969SSiddharth Bhat   /// \note
427abed4969SSiddharth Bhat   /// This is to be used only with managed memory
428abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
429abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
430abed4969SSiddharth Bhat 
43179a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
43279a947c2STobias Grosser   ///
43379a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
43479a947c2STobias Grosser   ///
43579a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
43679a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
43779a947c2STobias Grosser 
438a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
439a90be207SSiddharth Bhat   /// parameters.
440a90be207SSiddharth Bhat   ///
441a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
442a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
443a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
444a90be207SSiddharth Bhat   ///                   parameter.
445a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
446a90be207SSiddharth Bhat                             int Index);
447a90be207SSiddharth Bhat 
44879a947c2STobias Grosser   /// Create kernel launch parameters.
44979a947c2STobias Grosser   ///
45079a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
45179a947c2STobias Grosser   /// @param F             The kernel function that has been created.
45257693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
45379a947c2STobias Grosser   ///
45479a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
45579a947c2STobias Grosser   ///          values that are passed to the kernel.
45657693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
45757693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
45879a947c2STobias Grosser 
459b513b491STobias Grosser   /// Create declarations for kernel variable.
460b513b491STobias Grosser   ///
461b513b491STobias Grosser   /// This includes shared memory declarations.
462b513b491STobias Grosser   ///
463b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
464b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
465b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
466b513b491STobias Grosser 
467c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
468c1c6a2a6STobias Grosser   ///
469c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
470c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
471c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
472c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
473c1c6a2a6STobias Grosser   /// as specified here.
474c1c6a2a6STobias Grosser   ///
475c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
476c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
477c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
478c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
479c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
480c1c6a2a6STobias Grosser                           Value *BlockDimZ);
481c1c6a2a6STobias Grosser 
48232837fe3STobias Grosser   /// Create GPU kernel.
48332837fe3STobias Grosser   ///
48432837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
48532837fe3STobias Grosser   ///
48632837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
48732837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
48832837fe3STobias Grosser 
48913c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
49013c78e4dSTobias Grosser   ///
49113c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
49213c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
49313c78e4dSTobias Grosser 
494aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
495aaabbbf8STobias Grosser   ///
496aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
497aaabbbf8STobias Grosser   ///
498aaabbbf8STobias Grosser   /// Example:
499aaabbbf8STobias Grosser   ///
500aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
501aaabbbf8STobias Grosser   ///     A[i + 42] += ...
502aaabbbf8STobias Grosser   ///
503aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
504aaabbbf8STobias Grosser   ///
505aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
506aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
507aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
508aaabbbf8STobias Grosser 
50900bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
51000bb5a99STobias Grosser   ///
51100bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
51200bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
51300bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
51400bb5a99STobias Grosser 
51532837fe3STobias Grosser   /// Create kernel function.
51632837fe3STobias Grosser   ///
51732837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
51832837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
51932837fe3STobias Grosser   /// start block of this newly created function.
52032837fe3STobias Grosser   ///
52132837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
522edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
523f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
524f291c8d5SSiddharth Bhat   ///                         kernel.
525edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
526f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
527f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
52832837fe3STobias Grosser 
52932837fe3STobias Grosser   /// Create the declaration of a kernel function.
53032837fe3STobias Grosser   ///
53132837fe3STobias Grosser   /// The kernel function takes as arguments:
53232837fe3STobias Grosser   ///
53332837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
534f6044bd0STobias Grosser   ///   - Host iterators
535c84a1995STobias Grosser   ///   - Parameters
53632837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
53732837fe3STobias Grosser   ///
53832837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
539edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
540edb885cbSTobias Grosser   ///
54132837fe3STobias Grosser   /// @returns The newly declared function.
542edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
543edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
54432837fe3STobias Grosser 
545472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
546472f9654STobias Grosser   ///
547472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
548472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
549472f9654STobias Grosser 
5502f3073b5SPhilipp Schaad   /// Insert function calls to retrieve the SPIR group/local ids.
5512f3073b5SPhilipp Schaad   ///
5522f3073b5SPhilipp Schaad   /// @param The kernel to generate the function calls for.
5532f3073b5SPhilipp Schaad   void insertKernelCallsSPIR(ppcg_kernel *Kernel);
5542f3073b5SPhilipp Schaad 
555f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
556f291c8d5SSiddharth Bhat   ///
557f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
558f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
559f291c8d5SSiddharth Bhat   ///
560f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
561f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
562f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
563f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
564f291c8d5SSiddharth Bhat   ///
565f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
566f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
567f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
568f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
569f291c8d5SSiddharth Bhat   ///
570f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
571f291c8d5SSiddharth Bhat   ///                         this kernel.
572f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
573f291c8d5SSiddharth Bhat 
574b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
575b513b491STobias Grosser   ///
576b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
577b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
578b513b491STobias Grosser 
579edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
580edb885cbSTobias Grosser   ///
581edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
582edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
583edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
584edb885cbSTobias Grosser 
5855260c041STobias Grosser   /// Create an in-kernel synchronization call.
5865260c041STobias Grosser   void createKernelSync();
5875260c041STobias Grosser 
58874dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
58974dc3cb4STobias Grosser   ///
59074dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
59174dc3cb4STobias Grosser   std::string createKernelASM();
59274dc3cb4STobias Grosser 
59374dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
59474dc3cb4STobias Grosser   ///
59574dc3cb4STobias Grosser   /// @param F The function to remove references to.
59674dc3cb4STobias Grosser   void clearDominators(Function *F);
59774dc3cb4STobias Grosser 
59874dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
59974dc3cb4STobias Grosser   ///
60074dc3cb4STobias Grosser   /// @param F The function to remove references to.
60174dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
60274dc3cb4STobias Grosser 
60374dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
60474dc3cb4STobias Grosser   ///
60574dc3cb4STobias Grosser   /// @param F The function to remove references to.
60674dc3cb4STobias Grosser   void clearLoops(Function *F);
60774dc3cb4STobias Grosser 
60832837fe3STobias Grosser   /// Finalize the generation of the kernel function.
60932837fe3STobias Grosser   ///
61032837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
61132837fe3STobias Grosser   /// dump its IR to stderr.
61257793596STobias Grosser   ///
61357793596STobias Grosser   /// @returns The Assembly string of the kernel.
61457793596STobias Grosser   std::string finalizeKernelFunction();
615fa7b0802STobias Grosser 
61651dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
61751dfc275STobias Grosser   ///
61851dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
619a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
62051dfc275STobias Grosser   /// the kernel terminates.
62151dfc275STobias Grosser   ///
62251dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
62351dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
62451dfc275STobias Grosser 
6257287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
626fa7b0802STobias Grosser   void allocateDeviceArrays();
627fa7b0802STobias Grosser 
6287287aeddSTobias Grosser   /// Free all allocated device arrays.
6297287aeddSTobias Grosser   void freeDeviceArrays();
6307287aeddSTobias Grosser 
631fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
632fa7b0802STobias Grosser   ///
633fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
634fa7b0802STobias Grosser   Value *createCallInitContext();
635fa7b0802STobias Grosser 
63679a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
63779a947c2STobias Grosser   ///
63879a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
63979a947c2STobias Grosser   ///
64079a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
64179a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
64279a947c2STobias Grosser 
643fa7b0802STobias Grosser   /// Create a call to free the GPU context.
644fa7b0802STobias Grosser   ///
645fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
646fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
647fa7b0802STobias Grosser 
6487287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6497287aeddSTobias Grosser   ///
6507287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6517287aeddSTobias Grosser   ///
6527287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
653fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6547287aeddSTobias Grosser 
6557287aeddSTobias Grosser   /// Create a call to free a device array.
6567287aeddSTobias Grosser   ///
6577287aeddSTobias Grosser   /// @param Array The device array to free.
6587287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
65913c78e4dSTobias Grosser 
66013c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
66113c78e4dSTobias Grosser   ///
66213c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
66313c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
66413c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
66513c78e4dSTobias Grosser                                       Value *Size);
66613c78e4dSTobias Grosser 
66713c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
66813c78e4dSTobias Grosser   ///
66913c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
67013c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
67113c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
67213c78e4dSTobias Grosser                                       Value *Size);
67357793596STobias Grosser 
674abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
675abed4969SSiddharth Bhat   /// \note
676abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
677abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
678abed4969SSiddharth Bhat 
67957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
68057793596STobias Grosser   ///
68157793596STobias Grosser   /// @param Buffer The string describing the kernel.
68257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
68357793596STobias Grosser   ///
68457793596STobias Grosser   /// @returns A pointer to a kernel object
68557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
68657793596STobias Grosser 
68757793596STobias Grosser   /// Create a call to free a GPU kernel.
68857793596STobias Grosser   ///
68957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
69057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
69179a947c2STobias Grosser 
69279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
69379a947c2STobias Grosser   ///
69479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
69579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
69679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
69779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
69879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
69979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
700a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
70179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
70279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
70379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
70479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
70579a947c2STobias Grosser                               Value *Parameters);
7061fb9b64dSTobias Grosser };
7071fb9b64dSTobias Grosser 
70879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
7091abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
7101abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
71179f13b9aSSingapuram Sanjay Srivallabh }
71279f13b9aSSingapuram Sanjay Srivallabh 
713fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
714750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
715750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
716750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
717750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
718750160e2STobias Grosser 
719fa7b0802STobias Grosser   GPUContext = createCallInitContext();
720abed4969SSiddharth Bhat 
721abed4969SSiddharth Bhat   if (!ManagedMemory)
722fa7b0802STobias Grosser     allocateDeviceArrays();
723fa7b0802STobias Grosser }
724fa7b0802STobias Grosser 
725fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
726abed4969SSiddharth Bhat   if (!ManagedMemory)
7277287aeddSTobias Grosser     freeDeviceArrays();
728abed4969SSiddharth Bhat 
729fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
730fa7b0802STobias Grosser   IslNodeBuilder::finalize();
731fa7b0802STobias Grosser }
732fa7b0802STobias Grosser 
733fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
734abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
735abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
736fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
737fa7b0802STobias Grosser 
738fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
739fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
74013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7417287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7427287aeddSTobias Grosser     DevArrayName.append(Array->name);
743fa7b0802STobias Grosser 
74413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
745aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
746aaabbbf8STobias Grosser     if (Offset)
747aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
748aaabbbf8STobias Grosser           ArraySize,
749aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
750aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7517287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7527287aeddSTobias Grosser     DevArray->setName(DevArrayName);
75313c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
754fa7b0802STobias Grosser   }
755fa7b0802STobias Grosser 
756fa7b0802STobias Grosser   isl_ast_build_free(Build);
757fa7b0802STobias Grosser }
758fa7b0802STobias Grosser 
759c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
760c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
761c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
762c1c6a2a6STobias Grosser 
763c1c6a2a6STobias Grosser   for (auto &F : *M) {
764c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
765c1c6a2a6STobias Grosser       continue;
766c1c6a2a6STobias Grosser 
767c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
768c1c6a2a6STobias Grosser 
769c1c6a2a6STobias Grosser     Metadata *Elements[] = {
770c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
771c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
772c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
773c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
774c1c6a2a6STobias Grosser     };
775c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
776c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
777c1c6a2a6STobias Grosser   }
778c1c6a2a6STobias Grosser }
779c1c6a2a6STobias Grosser 
7807287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
781abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
78213c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
78313c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
7847287aeddSTobias Grosser }
7857287aeddSTobias Grosser 
78657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
78757793596STobias Grosser   const char *Name = "polly_getKernel";
78857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
78957793596STobias Grosser   Function *F = M->getFunction(Name);
79057793596STobias Grosser 
79157793596STobias Grosser   // If F is not available, declare it.
79257793596STobias Grosser   if (!F) {
79357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
79457793596STobias Grosser     std::vector<Type *> Args;
79557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
79657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
79757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
79857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
79957793596STobias Grosser   }
80057793596STobias Grosser 
80157793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
80257793596STobias Grosser }
80357793596STobias Grosser 
80479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
80579a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
80679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
80779a947c2STobias Grosser   Function *F = M->getFunction(Name);
80879a947c2STobias Grosser 
80979a947c2STobias Grosser   // If F is not available, declare it.
81079a947c2STobias Grosser   if (!F) {
81179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
81279a947c2STobias Grosser     std::vector<Type *> Args;
81379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
81479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
81579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
81679a947c2STobias Grosser   }
81779a947c2STobias Grosser 
81879a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
81979a947c2STobias Grosser }
82079a947c2STobias Grosser 
82179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
82279a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
82379a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
82479a947c2STobias Grosser                                             Value *Parameters) {
82579a947c2STobias Grosser   const char *Name = "polly_launchKernel";
82679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
82779a947c2STobias Grosser   Function *F = M->getFunction(Name);
82879a947c2STobias Grosser 
82979a947c2STobias Grosser   // If F is not available, declare it.
83079a947c2STobias Grosser   if (!F) {
83179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
83279a947c2STobias Grosser     std::vector<Type *> Args;
83379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
83479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
83979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
84079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
84179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
84279a947c2STobias Grosser   }
84379a947c2STobias Grosser 
844ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
84579a947c2STobias Grosser                          BlockDimZ, Parameters});
84679a947c2STobias Grosser }
84779a947c2STobias Grosser 
84857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
84957793596STobias Grosser   const char *Name = "polly_freeKernel";
85057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
85157793596STobias Grosser   Function *F = M->getFunction(Name);
85257793596STobias Grosser 
85357793596STobias Grosser   // If F is not available, declare it.
85457793596STobias Grosser   if (!F) {
85557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
85657793596STobias Grosser     std::vector<Type *> Args;
85757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
85857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
85957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
86057793596STobias Grosser   }
86157793596STobias Grosser 
86257793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
86357793596STobias Grosser }
86457793596STobias Grosser 
8657287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
866abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
867abed4969SSiddharth Bhat                            "for device");
8687287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8697287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8707287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8717287aeddSTobias Grosser 
8727287aeddSTobias Grosser   // If F is not available, declare it.
8737287aeddSTobias Grosser   if (!F) {
8747287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8757287aeddSTobias Grosser     std::vector<Type *> Args;
8767287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8777287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8787287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8797287aeddSTobias Grosser   }
8807287aeddSTobias Grosser 
8817287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
8827287aeddSTobias Grosser }
8837287aeddSTobias Grosser 
884fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
885abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
886abed4969SSiddharth Bhat                            "for device");
887fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
888fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
889fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
890fa7b0802STobias Grosser 
891fa7b0802STobias Grosser   // If F is not available, declare it.
892fa7b0802STobias Grosser   if (!F) {
893fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
894fa7b0802STobias Grosser     std::vector<Type *> Args;
895fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
896fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
897fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
898fa7b0802STobias Grosser   }
899fa7b0802STobias Grosser 
900fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
901fa7b0802STobias Grosser }
902fa7b0802STobias Grosser 
90313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
90413c78e4dSTobias Grosser                                                     Value *DeviceData,
90513c78e4dSTobias Grosser                                                     Value *Size) {
906abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
907abed4969SSiddharth Bhat                            "device and host");
90813c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
90913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
91013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
91113c78e4dSTobias Grosser 
91213c78e4dSTobias Grosser   // If F is not available, declare it.
91313c78e4dSTobias Grosser   if (!F) {
91413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
91513c78e4dSTobias Grosser     std::vector<Type *> Args;
91613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
91813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
91913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
92013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
92113c78e4dSTobias Grosser   }
92213c78e4dSTobias Grosser 
92313c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
92413c78e4dSTobias Grosser }
92513c78e4dSTobias Grosser 
92613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
92713c78e4dSTobias Grosser                                                     Value *HostData,
92813c78e4dSTobias Grosser                                                     Value *Size) {
929abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
930abed4969SSiddharth Bhat                            "device and host");
93113c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
93213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
93313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
93413c78e4dSTobias Grosser 
93513c78e4dSTobias Grosser   // If F is not available, declare it.
93613c78e4dSTobias Grosser   if (!F) {
93713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
93813c78e4dSTobias Grosser     std::vector<Type *> Args;
93913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
94013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
94113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
94213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
94313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
94413c78e4dSTobias Grosser   }
94513c78e4dSTobias Grosser 
94613c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
94713c78e4dSTobias Grosser }
94813c78e4dSTobias Grosser 
949abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
950abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
951abed4969SSiddharth Bhat                           "managed memory");
952abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
953abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
954abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
955abed4969SSiddharth Bhat 
956abed4969SSiddharth Bhat   // If F is not available, declare it.
957abed4969SSiddharth Bhat   if (!F) {
958abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
959abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
960abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
961abed4969SSiddharth Bhat   }
962abed4969SSiddharth Bhat 
963abed4969SSiddharth Bhat   Builder.CreateCall(F);
964abed4969SSiddharth Bhat }
965abed4969SSiddharth Bhat 
966fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
96717f01968SSiddharth Bhat   const char *Name;
96817f01968SSiddharth Bhat 
96917f01968SSiddharth Bhat   switch (Runtime) {
97017f01968SSiddharth Bhat   case GPURuntime::CUDA:
97117f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
97217f01968SSiddharth Bhat     break;
97317f01968SSiddharth Bhat   case GPURuntime::OpenCL:
97417f01968SSiddharth Bhat     Name = "polly_initContextCL";
97517f01968SSiddharth Bhat     break;
97617f01968SSiddharth Bhat   }
97717f01968SSiddharth Bhat 
978fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
979fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
980fa7b0802STobias Grosser 
981fa7b0802STobias Grosser   // If F is not available, declare it.
982fa7b0802STobias Grosser   if (!F) {
983fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
984fa7b0802STobias Grosser     std::vector<Type *> Args;
985fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
986fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
987fa7b0802STobias Grosser   }
988fa7b0802STobias Grosser 
989fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
990fa7b0802STobias Grosser }
991fa7b0802STobias Grosser 
992fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
993fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
994fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
995fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
996fa7b0802STobias Grosser 
997fa7b0802STobias Grosser   // If F is not available, declare it.
998fa7b0802STobias Grosser   if (!F) {
999fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1000fa7b0802STobias Grosser     std::vector<Type *> Args;
1001fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
1002fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1003fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
1004fa7b0802STobias Grosser   }
1005fa7b0802STobias Grosser 
1006fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
1007fa7b0802STobias Grosser }
1008fa7b0802STobias Grosser 
10095260c041STobias Grosser /// Check if one string is a prefix of another.
10105260c041STobias Grosser ///
10115260c041STobias Grosser /// @param String The string in which to look for the prefix.
10125260c041STobias Grosser /// @param Prefix The prefix to look for.
10135260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
10145260c041STobias Grosser   return String.find(Prefix) == 0;
10155260c041STobias Grosser }
10165260c041STobias Grosser 
101713c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1018f7face4bSSiddharth Bhat   isl::ast_build Build =
1019f7face4bSSiddharth Bhat       isl::ast_build::from_context(isl::manage(S.getContext()));
102013c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
102113c78e4dSTobias Grosser 
102213c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
1023f7face4bSSiddharth Bhat     isl::multi_pw_aff ArrayBound =
1024f7face4bSSiddharth Bhat         isl::manage(isl_multi_pw_aff_copy(Array->bound));
1025f7face4bSSiddharth Bhat 
1026f7face4bSSiddharth Bhat     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1027f7face4bSSiddharth Bhat     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
102813c78e4dSTobias Grosser 
102913c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
1030f7face4bSSiddharth Bhat       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1031f7face4bSSiddharth Bhat       isl::ast_expr Expr = Build.expr_from(Bound_I);
1032f7face4bSSiddharth Bhat       Res = Res.mul(Expr);
103313c78e4dSTobias Grosser     }
103413c78e4dSTobias Grosser 
1035f7face4bSSiddharth Bhat     Value *NumElements = ExprBuilder.create(Res.release());
1036b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1037b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
103813c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
103913c78e4dSTobias Grosser   }
104013c78e4dSTobias Grosser   return ArraySize;
104113c78e4dSTobias Grosser }
104213c78e4dSTobias Grosser 
1043aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1044aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1045aaabbbf8STobias Grosser     return nullptr;
1046aaabbbf8STobias Grosser 
1047aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
1048aaabbbf8STobias Grosser 
1049aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
1050aaabbbf8STobias Grosser 
1051aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
1052aaabbbf8STobias Grosser 
1053aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
1054aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
1055aaabbbf8STobias Grosser 
1056aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
1057aaabbbf8STobias Grosser     isl_set_free(Min);
1058aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
1059aaabbbf8STobias Grosser     isl_ast_build_free(Build);
1060aaabbbf8STobias Grosser     return nullptr;
1061aaabbbf8STobias Grosser   }
1062aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
1063aaabbbf8STobias Grosser 
1064aaabbbf8STobias Grosser   isl_ast_expr *Result =
1065aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
1066aaabbbf8STobias Grosser 
1067aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
1068aaabbbf8STobias Grosser     if (i > 0) {
10699e3db2b7SSiddharth Bhat       isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1);
1070aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
1071aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
1072aaabbbf8STobias Grosser     }
1073aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
1074aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
1075aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
1076aaabbbf8STobias Grosser   }
1077aaabbbf8STobias Grosser 
1078aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
1079aaabbbf8STobias Grosser   isl_set_free(Min);
1080aaabbbf8STobias Grosser   isl_ast_build_free(Build);
1081aaabbbf8STobias Grosser 
1082aaabbbf8STobias Grosser   return ResultValue;
1083aaabbbf8STobias Grosser }
1084aaabbbf8STobias Grosser 
1085abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1086abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1087abed4969SSiddharth Bhat 
1088abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1089abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1090abed4969SSiddharth Bhat                           "with managed memory");
1091abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1092abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1093abed4969SSiddharth Bhat     return it->second;
1094abed4969SSiddharth Bhat   } else {
1095abed4969SSiddharth Bhat     Value *HostPtr;
1096abed4969SSiddharth Bhat 
1097abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1098abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1099abed4969SSiddharth Bhat     else
1100abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1101abed4969SSiddharth Bhat 
1102abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1103abed4969SSiddharth Bhat     if (Offset) {
1104abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1105abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1106abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1107abed4969SSiddharth Bhat     }
1108abed4969SSiddharth Bhat 
1109abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1110abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1111abed4969SSiddharth Bhat     return HostPtr;
1112abed4969SSiddharth Bhat   }
1113abed4969SSiddharth Bhat }
1114abed4969SSiddharth Bhat 
111513c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
111613c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1117abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
111813c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
111913c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
112013c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
112113c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
112213c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
112313c78e4dSTobias Grosser 
112413c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1125aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
112613c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
112713c78e4dSTobias Grosser 
1128b06ff457STobias Grosser   Value *HostPtr;
1129b06ff457STobias Grosser 
1130b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1131b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1132b06ff457STobias Grosser   else
1133b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
113413c78e4dSTobias Grosser 
1135aaabbbf8STobias Grosser   if (Offset) {
1136aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1137aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1138aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1139aaabbbf8STobias Grosser   }
1140aaabbbf8STobias Grosser 
114113c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
114213c78e4dSTobias Grosser 
1143aaabbbf8STobias Grosser   if (Offset) {
1144aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1145ff40087aSTobias Grosser         Size, Builder.CreateMul(
1146ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1147aaabbbf8STobias Grosser   }
1148aaabbbf8STobias Grosser 
114913c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
115013c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
115113c78e4dSTobias Grosser   else
115213c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
115313c78e4dSTobias Grosser 
115413c78e4dSTobias Grosser   isl_id_free(Id);
115513c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
115613c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
115713c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
115813c78e4dSTobias Grosser }
115913c78e4dSTobias Grosser 
11601fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
116132837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
116232837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
116332837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
116432837fe3STobias Grosser   isl_id_free(Id);
116532837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
116632837fe3STobias Grosser 
116732837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
116832837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
116932837fe3STobias Grosser     createKernel(UserStmt);
117032837fe3STobias Grosser     isl_ast_expr_free(Expr);
117132837fe3STobias Grosser     return;
117232837fe3STobias Grosser   }
11739e3db2b7SSiddharth Bhat   if (!strcmp(Str, "init_device")) {
11749e3db2b7SSiddharth Bhat     initializeAfterRTH();
11759e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11769e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11779e3db2b7SSiddharth Bhat     return;
11789e3db2b7SSiddharth Bhat   }
11799e3db2b7SSiddharth Bhat   if (!strcmp(Str, "clear_device")) {
11809e3db2b7SSiddharth Bhat     finalize();
11819e3db2b7SSiddharth Bhat     isl_ast_node_free(UserStmt);
11829e3db2b7SSiddharth Bhat     isl_ast_expr_free(Expr);
11839e3db2b7SSiddharth Bhat     return;
11849e3db2b7SSiddharth Bhat   }
118513c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1186abed4969SSiddharth Bhat     if (!ManagedMemory)
118713c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1188abed4969SSiddharth Bhat     else
1189abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1190abed4969SSiddharth Bhat 
119132837fe3STobias Grosser     isl_ast_expr_free(Expr);
119213c78e4dSTobias Grosser     return;
119313c78e4dSTobias Grosser   }
119413c78e4dSTobias Grosser 
119513c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1196abed4969SSiddharth Bhat     if (!ManagedMemory) {
119713c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1198abed4969SSiddharth Bhat     } else {
1199abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1200abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1201abed4969SSiddharth Bhat     }
120213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
120338fc0aedSTobias Grosser     return;
120438fc0aedSTobias Grosser   }
120538fc0aedSTobias Grosser 
12065260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
12075260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
12085260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
12095260c041STobias Grosser   isl_id_free(Anno);
12105260c041STobias Grosser 
12115260c041STobias Grosser   switch (KernelStmt->type) {
12125260c041STobias Grosser   case ppcg_kernel_domain:
1213edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
12145260c041STobias Grosser     isl_ast_node_free(UserStmt);
12155260c041STobias Grosser     return;
12165260c041STobias Grosser   case ppcg_kernel_copy:
1217b513b491STobias Grosser     createKernelCopy(KernelStmt);
12185260c041STobias Grosser     isl_ast_expr_free(Expr);
12195260c041STobias Grosser     isl_ast_node_free(UserStmt);
12205260c041STobias Grosser     return;
12215260c041STobias Grosser   case ppcg_kernel_sync:
12225260c041STobias Grosser     createKernelSync();
12235260c041STobias Grosser     isl_ast_expr_free(Expr);
12245260c041STobias Grosser     isl_ast_node_free(UserStmt);
12255260c041STobias Grosser     return;
12265260c041STobias Grosser   }
12275260c041STobias Grosser 
12285260c041STobias Grosser   isl_ast_expr_free(Expr);
12295260c041STobias Grosser   isl_ast_node_free(UserStmt);
12305260c041STobias Grosser   return;
12315260c041STobias Grosser }
1232b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1233b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1234b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1235b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1236b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1237b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1238b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1239b513b491STobias Grosser 
1240b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1241b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1242b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1243b513b491STobias Grosser   } else {
1244b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1245b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1246b513b491STobias Grosser   }
1247b513b491STobias Grosser }
12485260c041STobias Grosser 
1249edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1250edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1251edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1252edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1253edb885cbSTobias Grosser 
1254edb885cbSTobias Grosser   LoopToScevMapT LTS;
1255edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1256edb885cbSTobias Grosser 
1257edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1258edb885cbSTobias Grosser 
1259edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1260edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1261edb885cbSTobias Grosser   else
1262a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1263edb885cbSTobias Grosser }
1264edb885cbSTobias Grosser 
12655260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12665260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12672f3073b5SPhilipp Schaad   const char *SpirName = "__gen_ocl_barrier_global";
126817f01968SSiddharth Bhat 
126917f01968SSiddharth Bhat   Function *Sync;
127017f01968SSiddharth Bhat 
127117f01968SSiddharth Bhat   switch (Arch) {
12722f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
12732f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
12742f3073b5SPhilipp Schaad     Sync = M->getFunction(SpirName);
12752f3073b5SPhilipp Schaad 
12762f3073b5SPhilipp Schaad     // If Sync is not available, declare it.
12772f3073b5SPhilipp Schaad     if (!Sync) {
12782f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
12792f3073b5SPhilipp Schaad       std::vector<Type *> Args;
12802f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
12812f3073b5SPhilipp Schaad       Sync = Function::Create(Ty, Linkage, SpirName, M);
12822f3073b5SPhilipp Schaad       Sync->setCallingConv(CallingConv::SPIR_FUNC);
12832f3073b5SPhilipp Schaad     }
12842f3073b5SPhilipp Schaad     break;
128517f01968SSiddharth Bhat   case GPUArch::NVPTX64:
128617f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
128717f01968SSiddharth Bhat     break;
128817f01968SSiddharth Bhat   }
128917f01968SSiddharth Bhat 
12905260c041STobias Grosser   Builder.CreateCall(Sync, {});
12915260c041STobias Grosser }
12925260c041STobias Grosser 
1293edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1294edb885cbSTobias Grosser ///
1295edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1296edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1297edb885cbSTobias Grosser ///
1298edb885cbSTobias Grosser /// @param Node The node to collect references for.
1299edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1300edb885cbSTobias Grosser ///
1301edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1302edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1303edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1304edb885cbSTobias Grosser     return isl_bool_true;
1305edb885cbSTobias Grosser 
1306edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1307edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1308edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1309edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1310edb885cbSTobias Grosser   isl_id_free(Id);
1311edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1312edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1313edb885cbSTobias Grosser 
1314edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1315edb885cbSTobias Grosser     return isl_bool_true;
1316edb885cbSTobias Grosser 
1317edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1318edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1319edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1320edb885cbSTobias Grosser   isl_id_free(Id);
1321edb885cbSTobias Grosser 
132200bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1323edb885cbSTobias Grosser 
1324edb885cbSTobias Grosser   return isl_bool_true;
1325edb885cbSTobias Grosser }
1326edb885cbSTobias Grosser 
1327f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
1328f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) {
1329f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1330f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
133154491db6STobias Grosser   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
133254491db6STobias Grosser   // "llvm.copysign".
133354491db6STobias Grosser   const StringRef Name = F->getName();
133454491db6STobias Grosser   return F->isIntrinsic() &&
133554491db6STobias Grosser          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
133654491db6STobias Grosser           Name.startswith("llvm.copysign"));
1337f291c8d5SSiddharth Bhat }
1338f291c8d5SSiddharth Bhat 
1339f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1340f291c8d5SSiddharth Bhat ///
1341f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1342f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1343f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1344f291c8d5SSiddharth Bhat /// `Function`s.
1345f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1346f291c8d5SSiddharth Bhat 
1347f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1348f291c8d5SSiddharth Bhat static SetVector<Function *>
1349f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1350f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1351f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1352f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1353f291c8d5SSiddharth Bhat     if (F) {
1354f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1355f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1356f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1357f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1358f291c8d5SSiddharth Bhat     }
1359f291c8d5SSiddharth Bhat   }
1360f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1361f291c8d5SSiddharth Bhat }
1362f291c8d5SSiddharth Bhat 
1363f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1364f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1365edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1366edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1367edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1368edb885cbSTobias Grosser   SubtreeReferences References = {
1369edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1370edb885cbSTobias Grosser 
1371edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1372edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1373edb885cbSTobias Grosser 
1374edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1375edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1376edb885cbSTobias Grosser 
1377edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1378edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1379edb885cbSTobias Grosser 
1380edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1381d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1382edb885cbSTobias Grosser 
1383edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1384edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1385edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1386edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1387edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1388edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1389edb885cbSTobias Grosser     isl_id_free(Id);
1390edb885cbSTobias Grosser   }
1391edb885cbSTobias Grosser   isl_space_free(Space);
1392edb885cbSTobias Grosser 
1393edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1394edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1395edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1396edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1397edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1398edb885cbSTobias Grosser     isl_id_free(Id);
1399edb885cbSTobias Grosser   }
1400edb885cbSTobias Grosser 
1401f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1402f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1403f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1404f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1405f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1406f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1407f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1408f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1409f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1410f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1411f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1412f291c8d5SSiddharth Bhat 
1413a1b2086aSSiddharth Bhat   // @see IslNodeBuilder::getReferencesInSubtree
1414a1b2086aSSiddharth Bhat   SetVector<Value *> ReplacedValues;
1415a1b2086aSSiddharth Bhat   for (Value *V : ValidSubtreeValues) {
1416a1b2086aSSiddharth Bhat     auto It = ValueMap.find(V);
1417a1b2086aSSiddharth Bhat     if (It == ValueMap.end())
1418a1b2086aSSiddharth Bhat       ReplacedValues.insert(V);
1419a1b2086aSSiddharth Bhat     else
1420a1b2086aSSiddharth Bhat       ReplacedValues.insert(It->second);
1421a1b2086aSSiddharth Bhat   }
1422a1b2086aSSiddharth Bhat   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1423edb885cbSTobias Grosser }
1424edb885cbSTobias Grosser 
142574dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
142674dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
142774dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
142874dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
142974dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
143074dc3cb4STobias Grosser 
143174dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
143274dc3cb4STobias Grosser     DT.eraseNode(BB);
143374dc3cb4STobias Grosser }
143474dc3cb4STobias Grosser 
143574dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
143674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
143774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
143874dc3cb4STobias Grosser     if (L)
143974dc3cb4STobias Grosser       SE.forgetLoop(L);
144074dc3cb4STobias Grosser   }
144174dc3cb4STobias Grosser }
144274dc3cb4STobias Grosser 
144374dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
144474dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
144574dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
144674dc3cb4STobias Grosser     if (L)
144774dc3cb4STobias Grosser       SE.forgetLoop(L);
144874dc3cb4STobias Grosser     LI.removeBlock(&BB);
144974dc3cb4STobias Grosser   }
145074dc3cb4STobias Grosser }
145174dc3cb4STobias Grosser 
145279a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
145379a947c2STobias Grosser   std::vector<Value *> Sizes;
145479a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
145579a947c2STobias Grosser 
145679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
145779a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
145879a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
145979a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
146079a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
146179a947c2STobias Grosser     Sizes.push_back(Res);
146279a947c2STobias Grosser   }
146379a947c2STobias Grosser   isl_ast_build_free(Context);
146479a947c2STobias Grosser 
146579a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
146679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
146779a947c2STobias Grosser 
146879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
146979a947c2STobias Grosser }
147079a947c2STobias Grosser 
147179a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
147279a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
147379a947c2STobias Grosser   std::vector<Value *> Sizes;
147479a947c2STobias Grosser 
147579a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
147679a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
147779a947c2STobias Grosser     Sizes.push_back(Res);
147879a947c2STobias Grosser   }
147979a947c2STobias Grosser 
148079a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
148179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
148279a947c2STobias Grosser 
148379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
148479a947c2STobias Grosser }
148579a947c2STobias Grosser 
1486a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1487a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1488a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1489a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1490a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1491a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1492a90be207SSiddharth Bhat }
1493a90be207SSiddharth Bhat 
149457693272STobias Grosser Value *
149557693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
149657693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1497a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1498a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1499a90be207SSiddharth Bhat 
1500a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
150179a947c2STobias Grosser 
150279a947c2STobias Grosser   BasicBlock *EntryBlock =
150379a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
150467726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
150579a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
150667726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
150767726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
150879a947c2STobias Grosser 
150979a947c2STobias Grosser   int Index = 0;
151079a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
151179a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
151279a947c2STobias Grosser       continue;
151379a947c2STobias Grosser 
151479a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1515206e9e3bSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
151679a947c2STobias Grosser 
1517a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1518a90be207SSiddharth Bhat 
1519abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1520abed4969SSiddharth Bhat     if (ManagedMemory) {
1521abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1522abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1523abed4969SSiddharth Bhat     } else {
1524abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
152579a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1526abed4969SSiddharth Bhat     }
1527abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1528abed4969SSiddharth Bhat                                   "initialized");
1529aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1530aaabbbf8STobias Grosser 
1531aaabbbf8STobias Grosser     if (Offset) {
1532aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1533aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1534aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1535aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1536aaabbbf8STobias Grosser     }
1537fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1538fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1539aaabbbf8STobias Grosser 
1540fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1541abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1542abed4969SSiddharth Bhat       if (ManagedMemory)
1543abed4969SSiddharth Bhat         ValPtr = DevArray;
1544abed4969SSiddharth Bhat       else
1545abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1546abed4969SSiddharth Bhat 
1547abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1548abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1549fe74a7a1STobias Grosser       Value *ValPtrCast =
1550fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1551fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1552fe74a7a1STobias Grosser     } else {
155367726b32STobias Grosser       Instruction *Param =
155467726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
155567726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
155679a947c2STobias Grosser                          EntryBlock->getTerminator());
155779a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
155879a947c2STobias Grosser       Value *ParamTyped =
155979a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
156079a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1561fe74a7a1STobias Grosser     }
156279a947c2STobias Grosser     Index++;
156379a947c2STobias Grosser   }
156479a947c2STobias Grosser 
1565a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1566a490147cSTobias Grosser 
1567a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1568a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1569a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1570a490147cSTobias Grosser     isl_id_free(Id);
1571a90be207SSiddharth Bhat 
1572a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1573a90be207SSiddharth Bhat 
157467726b32STobias Grosser     Instruction *Param =
157567726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
157667726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1577a490147cSTobias Grosser                        EntryBlock->getTerminator());
1578a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1579a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1580a490147cSTobias Grosser     Index++;
1581a490147cSTobias Grosser   }
1582a490147cSTobias Grosser 
1583d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1584d8b94bcaSTobias Grosser 
1585d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1586d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1587d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1588a1b2086aSSiddharth Bhat     if (ValueMap.count(Val))
1589a1b2086aSSiddharth Bhat       Val = ValueMap[Val];
1590d8b94bcaSTobias Grosser     isl_id_free(Id);
1591a90be207SSiddharth Bhat 
1592a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1593a90be207SSiddharth Bhat 
159467726b32STobias Grosser     Instruction *Param =
159567726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
159667726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1597d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1598d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1599a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1600d8b94bcaSTobias Grosser     Index++;
1601d8b94bcaSTobias Grosser   }
1602d8b94bcaSTobias Grosser 
160357693272STobias Grosser   for (auto Val : SubtreeValues) {
1604a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1605a90be207SSiddharth Bhat 
160667726b32STobias Grosser     Instruction *Param =
160767726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
160867726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
160957693272STobias Grosser                        EntryBlock->getTerminator());
161057693272STobias Grosser     Builder.CreateStore(Val, Param);
1611a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1612a90be207SSiddharth Bhat     Index++;
1613a90be207SSiddharth Bhat   }
1614a90be207SSiddharth Bhat 
1615a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1616a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1617a90be207SSiddharth Bhat     Instruction *Param =
1618a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1619a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1620a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1621a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1622a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
162357693272STobias Grosser     Index++;
162457693272STobias Grosser   }
162557693272STobias Grosser 
162679a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
162779a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
162879a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
162979a947c2STobias Grosser }
163079a947c2STobias Grosser 
1631f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1632f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1633f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1634f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1635f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1636f291c8d5SSiddharth Bhat     if (!Clone)
1637f291c8d5SSiddharth Bhat       Clone =
1638f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1639f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1640f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1641f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1642f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1643f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1644f291c8d5SSiddharth Bhat   }
1645f291c8d5SSiddharth Bhat }
164632837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
164732837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
164832837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
164932837fe3STobias Grosser   isl_id_free(Id);
165032837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
165132837fe3STobias Grosser 
1652bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1653bc653f20STobias Grosser     DeepestParallel =
1654bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1655bc653f20STobias Grosser   else
1656bc653f20STobias Grosser     DeepestSequential =
1657bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1658bc653f20STobias Grosser 
1659c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1660c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1661c1c6a2a6STobias Grosser 
1662f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1663f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1664f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1665edb885cbSTobias Grosser 
166632837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
166732837fe3STobias Grosser 
166832837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1669472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1670edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1671587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1672b06ff457STobias Grosser   ScalarMap.clear();
167332837fe3STobias Grosser 
1674edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1675edb885cbSTobias Grosser 
1676edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1677edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1678edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1679edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1680edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1681edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1682edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1683edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1684edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1685edb885cbSTobias Grosser     SubtreeValues.insert(V);
1686edb885cbSTobias Grosser   }
1687edb885cbSTobias Grosser 
1688f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1689f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
169032837fe3STobias Grosser 
169159ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
169259ab0705STobias Grosser 
169351dfc275STobias Grosser   finalizeKernelArguments(Kernel);
169474dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
16952f3073b5SPhilipp Schaad   if (Arch == GPUArch::NVPTX64)
1696c1c6a2a6STobias Grosser     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
169774dc3cb4STobias Grosser   clearDominators(F);
169874dc3cb4STobias Grosser   clearScalarEvolution(F);
169974dc3cb4STobias Grosser   clearLoops(F);
170074dc3cb4STobias Grosser 
1701472f9654STobias Grosser   IDToValue = HostIDs;
170232837fe3STobias Grosser 
1703b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1704b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1705edb885cbSTobias Grosser   EscapeMap.clear();
1706edb885cbSTobias Grosser   IDToSAI.clear();
170774dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
170874dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
17094d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
171074dc3cb4STobias Grosser   LocalArrays.clear();
1711edb885cbSTobias Grosser 
171251dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
171351dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
171457693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
171579a947c2STobias Grosser 
171679f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
171757793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
171857793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
171957793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
172079a947c2STobias Grosser 
172179a947c2STobias Grosser   Value *GridDimX, *GridDimY;
172279a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
172379a947c2STobias Grosser 
172479a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
172579a947c2STobias Grosser                          BlockDimZ, Parameters);
172657793596STobias Grosser   createCallFreeKernel(GPUKernel);
1727b513b491STobias Grosser 
1728b513b491STobias Grosser   for (auto Id : KernelIds)
1729b513b491STobias Grosser     isl_id_free(Id);
1730b513b491STobias Grosser 
1731b513b491STobias Grosser   KernelIds.clear();
173232837fe3STobias Grosser }
173332837fe3STobias Grosser 
173432837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
173532837fe3STobias Grosser ///
173632837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
173732837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1738d277fedaSSiddharth Bhat   std::string Ret = "";
173932837fe3STobias Grosser 
1740d277fedaSSiddharth Bhat   if (!is64Bit) {
1741d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
174230caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1743d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1744d277fedaSSiddharth Bhat   } else {
1745d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
174630caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1747d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1748d277fedaSSiddharth Bhat   }
174932837fe3STobias Grosser 
175032837fe3STobias Grosser   return Ret;
175132837fe3STobias Grosser }
175232837fe3STobias Grosser 
17532f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel.
17542f3073b5SPhilipp Schaad ///
17552f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture?
17562f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) {
17572f3073b5SPhilipp Schaad   std::string Ret = "";
17582f3073b5SPhilipp Schaad 
17592f3073b5SPhilipp Schaad   if (!is64Bit) {
17602f3073b5SPhilipp Schaad     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
176130caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17622f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17632f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17642f3073b5SPhilipp Schaad   } else {
17652f3073b5SPhilipp Schaad     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
176630caae6dSTobias Grosser            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
17672f3073b5SPhilipp Schaad            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
17682f3073b5SPhilipp Schaad            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
17692f3073b5SPhilipp Schaad   }
17702f3073b5SPhilipp Schaad 
17712f3073b5SPhilipp Schaad   return Ret;
17722f3073b5SPhilipp Schaad }
17732f3073b5SPhilipp Schaad 
1774edb885cbSTobias Grosser Function *
1775edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1776edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
177732837fe3STobias Grosser   std::vector<Type *> Args;
177879f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
177932837fe3STobias Grosser 
17802f3073b5SPhilipp Schaad   std::vector<Metadata *> MemoryType;
17812f3073b5SPhilipp Schaad 
178232837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
178332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
178432837fe3STobias Grosser       continue;
178532837fe3STobias Grosser 
1786fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1787fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1788206e9e3bSTobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1789fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
17902f3073b5SPhilipp Schaad       MemoryType.push_back(
17912f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1792fe74a7a1STobias Grosser     } else {
1793d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1794d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
17952f3073b5SPhilipp Schaad       MemoryType.push_back(
17962f3073b5SPhilipp Schaad           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
179732837fe3STobias Grosser     }
1798fe74a7a1STobias Grosser   }
179932837fe3STobias Grosser 
1800f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1801f6044bd0STobias Grosser 
18022f3073b5SPhilipp Schaad   for (long i = 0; i < NumHostIters; i++) {
1803f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
18042f3073b5SPhilipp Schaad     MemoryType.push_back(
18052f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18062f3073b5SPhilipp Schaad   }
1807f6044bd0STobias Grosser 
1808c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1809c84a1995STobias Grosser 
1810cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1811cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1812cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1813cf66ef26STobias Grosser     isl_id_free(Id);
1814cf66ef26STobias Grosser     Args.push_back(Val->getType());
18152f3073b5SPhilipp Schaad     MemoryType.push_back(
18162f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1817cf66ef26STobias Grosser   }
1818c84a1995STobias Grosser 
18192f3073b5SPhilipp Schaad   for (auto *V : SubtreeValues) {
1820edb885cbSTobias Grosser     Args.push_back(V->getType());
18212f3073b5SPhilipp Schaad     MemoryType.push_back(
18222f3073b5SPhilipp Schaad         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
18232f3073b5SPhilipp Schaad   }
1824edb885cbSTobias Grosser 
182532837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
182632837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
182732837fe3STobias Grosser                               GPUModule.get());
182817f01968SSiddharth Bhat 
18292f3073b5SPhilipp Schaad   std::vector<Metadata *> EmptyStrings;
18302f3073b5SPhilipp Schaad 
18312f3073b5SPhilipp Schaad   for (unsigned int i = 0; i < MemoryType.size(); i++) {
18322f3073b5SPhilipp Schaad     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
18332f3073b5SPhilipp Schaad   }
18342f3073b5SPhilipp Schaad 
18352f3073b5SPhilipp Schaad   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
18362f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_addr_space",
18372f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), MemoryType));
18382f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_name",
18392f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18402f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_access_qual",
18412f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18422f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type",
18432f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18442f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_type_qual",
18452f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18462f3073b5SPhilipp Schaad     FN->setMetadata("kernel_arg_base_type",
18472f3073b5SPhilipp Schaad                     MDNode::get(FN->getContext(), EmptyStrings));
18482f3073b5SPhilipp Schaad   }
18492f3073b5SPhilipp Schaad 
185017f01968SSiddharth Bhat   switch (Arch) {
185117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
185232837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
185317f01968SSiddharth Bhat     break;
18542f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
18552f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
18562f3073b5SPhilipp Schaad     FN->setCallingConv(CallingConv::SPIR_KERNEL);
18572f3073b5SPhilipp Schaad     break;
185817f01968SSiddharth Bhat   }
185932837fe3STobias Grosser 
186032837fe3STobias Grosser   auto Arg = FN->arg_begin();
186132837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
186232837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
186332837fe3STobias Grosser       continue;
186432837fe3STobias Grosser 
1865edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1866edb885cbSTobias Grosser 
1867edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1868206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
1869206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
1870edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1871edb885cbSTobias Grosser     Value *Val = &*Arg;
1872edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1873edb885cbSTobias Grosser     isl_ast_build *Build =
1874edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1875f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1876edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1877edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
18789e3db2b7SSiddharth Bhat           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1879edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1880edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1881edb885cbSTobias Grosser     }
1882edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
18834d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
188474dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1885edb885cbSTobias Grosser 
1886edb885cbSTobias Grosser     isl_ast_build_free(Build);
1887b513b491STobias Grosser     KernelIds.push_back(Id);
1888edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
188932837fe3STobias Grosser     Arg++;
189032837fe3STobias Grosser   }
189132837fe3STobias Grosser 
1892f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1893f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1894f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1895f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1896f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1897f6044bd0STobias Grosser     Arg++;
1898f6044bd0STobias Grosser   }
1899f6044bd0STobias Grosser 
1900c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1901c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1902c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
190312453403STobias Grosser     Value *Val = IDToValue[Id];
190412453403STobias Grosser     ValueMap[Val] = &*Arg;
1905c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1906c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1907c84a1995STobias Grosser     Arg++;
1908c84a1995STobias Grosser   }
1909c84a1995STobias Grosser 
1910edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1911edb885cbSTobias Grosser     Arg->setName(V->getName());
1912edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1913edb885cbSTobias Grosser     Arg++;
1914edb885cbSTobias Grosser   }
1915edb885cbSTobias Grosser 
191632837fe3STobias Grosser   return FN;
191732837fe3STobias Grosser }
191832837fe3STobias Grosser 
1919472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
192017f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
192117f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1922472f9654STobias Grosser 
192317f01968SSiddharth Bhat   switch (Arch) {
19242f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
19252f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
19262f3073b5SPhilipp Schaad     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
192717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
192817f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
192917f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
193017f01968SSiddharth Bhat 
193117f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
193217f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
193317f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
193417f01968SSiddharth Bhat     break;
193517f01968SSiddharth Bhat   }
1936472f9654STobias Grosser 
1937472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1938472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1939472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1940472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1941472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1942472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1943472f9654STobias Grosser     IDToValue[Id] = Val;
1944472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1945472f9654STobias Grosser   };
1946472f9654STobias Grosser 
1947472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1948472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1949472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1950472f9654STobias Grosser   }
1951472f9654STobias Grosser 
1952472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1953472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1954472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1955472f9654STobias Grosser   }
1956472f9654STobias Grosser }
1957472f9654STobias Grosser 
19582f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) {
19592f3073b5SPhilipp Schaad   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
19602f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id1",
19612f3073b5SPhilipp Schaad                               "__gen_ocl_get_group_id2"};
19622f3073b5SPhilipp Schaad 
19632f3073b5SPhilipp Schaad   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
19642f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id1",
19652f3073b5SPhilipp Schaad                               "__gen_ocl_get_local_id2"};
19662f3073b5SPhilipp Schaad 
19672f3073b5SPhilipp Schaad   auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable {
19682f3073b5SPhilipp Schaad     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19692f3073b5SPhilipp Schaad     Function *FN = M->getFunction(Name);
19702f3073b5SPhilipp Schaad 
19712f3073b5SPhilipp Schaad     // If FN is not available, declare it.
19722f3073b5SPhilipp Schaad     if (!FN) {
19732f3073b5SPhilipp Schaad       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
19742f3073b5SPhilipp Schaad       std::vector<Type *> Args;
19752f3073b5SPhilipp Schaad       FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false);
19762f3073b5SPhilipp Schaad       FN = Function::Create(Ty, Linkage, Name, M);
19772f3073b5SPhilipp Schaad       FN->setCallingConv(CallingConv::SPIR_FUNC);
19782f3073b5SPhilipp Schaad     }
19792f3073b5SPhilipp Schaad 
19802f3073b5SPhilipp Schaad     Value *Val = Builder.CreateCall(FN, {});
19812f3073b5SPhilipp Schaad     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
19822f3073b5SPhilipp Schaad     IDToValue[Id] = Val;
19832f3073b5SPhilipp Schaad     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
19842f3073b5SPhilipp Schaad   };
19852f3073b5SPhilipp Schaad 
19862f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_grid; ++i)
19872f3073b5SPhilipp Schaad     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i));
19882f3073b5SPhilipp Schaad 
19892f3073b5SPhilipp Schaad   for (int i = 0; i < Kernel->n_block; ++i)
19902f3073b5SPhilipp Schaad     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i));
19912f3073b5SPhilipp Schaad }
19922f3073b5SPhilipp Schaad 
199300bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
199400bb5a99STobias Grosser   auto Arg = FN->arg_begin();
199500bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
199600bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
199700bb5a99STobias Grosser       continue;
199800bb5a99STobias Grosser 
199900bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2000206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2001206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
200200bb5a99STobias Grosser     isl_id_free(Id);
200300bb5a99STobias Grosser 
200400bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
200500bb5a99STobias Grosser       Arg++;
200600bb5a99STobias Grosser       continue;
200700bb5a99STobias Grosser     }
200800bb5a99STobias Grosser 
2009fe74a7a1STobias Grosser     Value *Val = &*Arg;
2010fe74a7a1STobias Grosser 
2011fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
201200bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
2013fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2014fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
2015fe74a7a1STobias Grosser     }
2016fe74a7a1STobias Grosser 
2017fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
201800bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
201900bb5a99STobias Grosser 
202000bb5a99STobias Grosser     Arg++;
202100bb5a99STobias Grosser   }
202200bb5a99STobias Grosser }
202300bb5a99STobias Grosser 
202451dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
202551dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
202651dfc275STobias Grosser   auto Arg = FN->arg_begin();
202751dfc275STobias Grosser 
202851dfc275STobias Grosser   bool StoredScalar = false;
202951dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
203051dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
203151dfc275STobias Grosser       continue;
203251dfc275STobias Grosser 
203351dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2034206e9e3bSTobias Grosser     const ScopArrayInfo *SAI =
2035206e9e3bSTobias Grosser         ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id)));
203651dfc275STobias Grosser     isl_id_free(Id);
203751dfc275STobias Grosser 
203851dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
203951dfc275STobias Grosser       Arg++;
204051dfc275STobias Grosser       continue;
204151dfc275STobias Grosser     }
204251dfc275STobias Grosser 
204351dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
204451dfc275STobias Grosser       Arg++;
204551dfc275STobias Grosser       continue;
204651dfc275STobias Grosser     }
204751dfc275STobias Grosser 
204851dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
204951dfc275STobias Grosser     Value *ArgPtr = &*Arg;
205051dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
205151dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
205251dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
205351dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
205451dfc275STobias Grosser     StoredScalar = true;
205551dfc275STobias Grosser 
205651dfc275STobias Grosser     Arg++;
205751dfc275STobias Grosser   }
205851dfc275STobias Grosser 
205951dfc275STobias Grosser   if (StoredScalar)
206051dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
206151dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
206251dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
206351dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
206451dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
206551dfc275STobias Grosser       BuildSuccessful = 0;
206651dfc275STobias Grosser }
206751dfc275STobias Grosser 
2068b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2069b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2070b513b491STobias Grosser 
2071b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
2072b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
2073b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2074206e9e3bSTobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2075b513b491STobias Grosser 
2076f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
2077b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
2078b513b491STobias Grosser 
2079f5aff704SRoman Gareev     Sizes.push_back(nullptr);
2080928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2081b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2082f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
2083b513b491STobias Grosser       isl_val_free(Val);
2084b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2085928d7573STobias Grosser     }
2086928d7573STobias Grosser 
2087928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2088928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2089928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
2090928d7573STobias Grosser       isl_val_free(Val);
2091b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
2092b513b491STobias Grosser     }
2093b513b491STobias Grosser 
2094130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
2095130ca30fSTobias Grosser     Value *Allocation;
2096130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
2097130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
2098130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2099130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2100130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
2101f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2102f919d8b3STobias Grosser 
2103130ca30fSTobias Grosser       Allocation = GlobalVar;
2104130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
2105130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2106130ca30fSTobias Grosser     } else {
2107130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
2108130ca30fSTobias Grosser     }
21094d5a9172STobias Grosser     SAI =
21104d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2111b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
2112130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
2113130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
2114b513b491STobias Grosser     KernelIds.push_back(Id);
2115b513b491STobias Grosser     IDToSAI[Id] = SAI;
2116b513b491STobias Grosser   }
2117b513b491STobias Grosser }
2118b513b491STobias Grosser 
2119f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
2120f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2121f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
212279f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
212332837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
212417f01968SSiddharth Bhat 
212517f01968SSiddharth Bhat   switch (Arch) {
212617f01968SSiddharth Bhat   case GPUArch::NVPTX64:
212717f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
212832837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
212917f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
213017f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
213132837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
213217f01968SSiddharth Bhat     break;
21332f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21342f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
21352f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
21362f3073b5SPhilipp Schaad     break;
21372f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21382f3073b5SPhilipp Schaad     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
21392f3073b5SPhilipp Schaad     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
21402f3073b5SPhilipp Schaad     break;
214117f01968SSiddharth Bhat   }
214232837fe3STobias Grosser 
2143edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
214432837fe3STobias Grosser 
214559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
214632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
214732837fe3STobias Grosser 
214859ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
214959ab0705STobias Grosser 
215032837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
215132837fe3STobias Grosser   Builder.CreateRetVoid();
215232837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2153472f9654STobias Grosser 
2154629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
2155629109b6STobias Grosser 
215600bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
2157b513b491STobias Grosser   createKernelVariables(Kernel, FN);
21582f3073b5SPhilipp Schaad 
21592f3073b5SPhilipp Schaad   switch (Arch) {
21602f3073b5SPhilipp Schaad   case GPUArch::NVPTX64:
2161472f9654STobias Grosser     insertKernelIntrinsics(Kernel);
21622f3073b5SPhilipp Schaad     break;
21632f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21642f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21652f3073b5SPhilipp Schaad     insertKernelCallsSPIR(Kernel);
21662f3073b5SPhilipp Schaad     break;
21672f3073b5SPhilipp Schaad   }
216832837fe3STobias Grosser }
216932837fe3STobias Grosser 
217074dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
217117f01968SSiddharth Bhat   llvm::Triple GPUTriple;
217217f01968SSiddharth Bhat 
217317f01968SSiddharth Bhat   switch (Arch) {
217417f01968SSiddharth Bhat   case GPUArch::NVPTX64:
217517f01968SSiddharth Bhat     switch (Runtime) {
217617f01968SSiddharth Bhat     case GPURuntime::CUDA:
217717f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
217817f01968SSiddharth Bhat       break;
217917f01968SSiddharth Bhat     case GPURuntime::OpenCL:
218017f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
218117f01968SSiddharth Bhat       break;
218217f01968SSiddharth Bhat     }
218317f01968SSiddharth Bhat     break;
21842f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
21852f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
21862f3073b5SPhilipp Schaad     std::string SPIRAssembly;
21872f3073b5SPhilipp Schaad     raw_string_ostream IROstream(SPIRAssembly);
21882f3073b5SPhilipp Schaad     IROstream << *GPUModule;
21892f3073b5SPhilipp Schaad     IROstream.flush();
21902f3073b5SPhilipp Schaad     return SPIRAssembly;
219117f01968SSiddharth Bhat   }
219217f01968SSiddharth Bhat 
219374dc3cb4STobias Grosser   std::string ErrMsg;
219474dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
219574dc3cb4STobias Grosser 
219674dc3cb4STobias Grosser   if (!GPUTarget) {
219774dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
219874dc3cb4STobias Grosser     return "";
219974dc3cb4STobias Grosser   }
220074dc3cb4STobias Grosser 
220174dc3cb4STobias Grosser   TargetOptions Options;
220274dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
220317f01968SSiddharth Bhat 
220417f01968SSiddharth Bhat   std::string subtarget;
220517f01968SSiddharth Bhat 
220617f01968SSiddharth Bhat   switch (Arch) {
220717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
220817f01968SSiddharth Bhat     subtarget = CudaVersion;
220917f01968SSiddharth Bhat     break;
22102f3073b5SPhilipp Schaad   case GPUArch::SPIR32:
22112f3073b5SPhilipp Schaad   case GPUArch::SPIR64:
22122f3073b5SPhilipp Schaad     llvm_unreachable("No subtarget for SPIR architecture");
221317f01968SSiddharth Bhat   }
221417f01968SSiddharth Bhat 
221517f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
221617f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
221774dc3cb4STobias Grosser 
221874dc3cb4STobias Grosser   SmallString<0> ASMString;
221974dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
222074dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
222174dc3cb4STobias Grosser 
222274dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
222374dc3cb4STobias Grosser 
222474dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
222574dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
222674dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
222774dc3cb4STobias Grosser     return "";
222874dc3cb4STobias Grosser   }
222974dc3cb4STobias Grosser 
223074dc3cb4STobias Grosser   PM.run(*GPUModule);
223174dc3cb4STobias Grosser 
223274dc3cb4STobias Grosser   return ASMStream.str();
223374dc3cb4STobias Grosser }
223474dc3cb4STobias Grosser 
223557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
223665d7f72fSSiddharth Bhat 
22375857b701STobias Grosser   if (verifyModule(*GPUModule)) {
223865d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
223965d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2240a0fb8b23SSiddharth Bhat     DEBUG(dbgs() << "verifyModule Error:\n";
2241a0fb8b23SSiddharth Bhat           verifyModule(*GPUModule, &dbgs()););
224265d7f72fSSiddharth Bhat 
224365d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
224465d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
224565d7f72fSSiddharth Bhat 
22465857b701STobias Grosser     BuildSuccessful = false;
22475857b701STobias Grosser     return "";
22485857b701STobias Grosser   }
224932837fe3STobias Grosser 
225032837fe3STobias Grosser   if (DumpKernelIR)
225132837fe3STobias Grosser     outs() << *GPUModule << "\n";
225232837fe3STobias Grosser 
22532f3073b5SPhilipp Schaad   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
22549a18d559STobias Grosser     // Optimize module.
22559a18d559STobias Grosser     llvm::legacy::PassManager OptPasses;
22569a18d559STobias Grosser     PassManagerBuilder PassBuilder;
22579a18d559STobias Grosser     PassBuilder.OptLevel = 3;
22589a18d559STobias Grosser     PassBuilder.SizeLevel = 0;
22599a18d559STobias Grosser     PassBuilder.populateModulePassManager(OptPasses);
22609a18d559STobias Grosser     OptPasses.run(*GPUModule);
22612f3073b5SPhilipp Schaad   }
22629a18d559STobias Grosser 
226374dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
226474dc3cb4STobias Grosser 
226574dc3cb4STobias Grosser   if (DumpKernelASM)
226674dc3cb4STobias Grosser     outs() << Assembly << "\n";
226774dc3cb4STobias Grosser 
226832837fe3STobias Grosser   GPUModule.release();
2269472f9654STobias Grosser   KernelIDs.clear();
227057793596STobias Grosser 
227157793596STobias Grosser   return Assembly;
227232837fe3STobias Grosser }
227332837fe3STobias Grosser 
22749dfe4e7cSTobias Grosser namespace {
22759dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
22769dfe4e7cSTobias Grosser public:
22779dfe4e7cSTobias Grosser   static char ID;
22789dfe4e7cSTobias Grosser 
227917f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
228017f01968SSiddharth Bhat 
228117f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
228217f01968SSiddharth Bhat 
2283e938517eSTobias Grosser   /// The scop that is currently processed.
2284e938517eSTobias Grosser   Scop *S;
2285e938517eSTobias Grosser 
228638fc0aedSTobias Grosser   LoopInfo *LI;
228738fc0aedSTobias Grosser   DominatorTree *DT;
228838fc0aedSTobias Grosser   ScalarEvolution *SE;
228938fc0aedSTobias Grosser   const DataLayout *DL;
229038fc0aedSTobias Grosser   RegionInfo *RI;
229138fc0aedSTobias Grosser 
22929dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
22939dfe4e7cSTobias Grosser 
2294e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2295e938517eSTobias Grosser   ///
2296e938517eSTobias Grosser   /// @returns The compilation options.
2297e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2298e938517eSTobias Grosser     auto DebugOptions =
2299e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2300e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2301e938517eSTobias Grosser 
2302e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2303e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2304e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2305e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
23068950ceadSTobias Grosser     DebugOptions->verbose = false;
2307e938517eSTobias Grosser 
2308e938517eSTobias Grosser     Options->debug = DebugOptions;
2309e938517eSTobias Grosser 
23109e3db2b7SSiddharth Bhat     Options->group_chains = false;
2311e938517eSTobias Grosser     Options->reschedule = true;
2312e938517eSTobias Grosser     Options->scale_tile_loops = false;
2313e938517eSTobias Grosser     Options->wrap = false;
2314e938517eSTobias Grosser 
2315e938517eSTobias Grosser     Options->non_negative_parameters = false;
2316e938517eSTobias Grosser     Options->ctx = nullptr;
2317e938517eSTobias Grosser     Options->sizes = nullptr;
2318e938517eSTobias Grosser 
23199e3db2b7SSiddharth Bhat     Options->tile = true;
23204eaedde5STobias Grosser     Options->tile_size = 32;
23214eaedde5STobias Grosser 
23229e3db2b7SSiddharth Bhat     Options->isolate_full_tiles = false;
23239e3db2b7SSiddharth Bhat 
2324130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2325b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2326b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2327e938517eSTobias Grosser 
2328e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2329e938517eSTobias Grosser     Options->openmp = false;
2330e938517eSTobias Grosser     Options->linearize_device_arrays = true;
23319e3db2b7SSiddharth Bhat     Options->allow_gnu_extensions = false;
2332e938517eSTobias Grosser 
23339e3db2b7SSiddharth Bhat     Options->unroll_copy_shared = false;
23349e3db2b7SSiddharth Bhat     Options->unroll_gpu_tile = false;
23359e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
23369e3db2b7SSiddharth Bhat 
23379e3db2b7SSiddharth Bhat     Options->live_range_reordering = true;
23389e3db2b7SSiddharth Bhat     Options->hybrid = false;
2339e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2340e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2341e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2342e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2343e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2344e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2345e938517eSTobias Grosser 
2346e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2347e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2348e938517eSTobias Grosser 
2349e938517eSTobias Grosser     return Options;
2350e938517eSTobias Grosser   }
2351e938517eSTobias Grosser 
2352f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2353f384594dSTobias Grosser   ///
2354f384594dSTobias Grosser   /// Instead of a normal access of the form:
2355f384594dSTobias Grosser   ///
2356f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2357f384594dSTobias Grosser   ///
2358f384594dSTobias Grosser   /// a tagged access has the form
2359f384594dSTobias Grosser   ///
2360f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2361f384594dSTobias Grosser   ///
2362f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2363f384594dSTobias Grosser   /// triggered the access.
2364f384594dSTobias Grosser   ///
2365f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2366f384594dSTobias Grosser   ///
2367f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2368f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2369f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2370f384594dSTobias Grosser 
2371f384594dSTobias Grosser     for (auto &Stmt : *S)
2372f384594dSTobias Grosser       for (auto &Acc : Stmt)
2373f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
23741515f6b9STobias Grosser           isl_map *Relation = Acc->getAccessRelation().release();
2375f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2376f384594dSTobias Grosser 
2377f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2378f384594dSTobias Grosser           Space = isl_space_range(Space);
2379f384594dSTobias Grosser           Space = isl_space_from_range(Space);
2380fe46c3ffSTobias Grosser           Space =
2381fe46c3ffSTobias Grosser               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2382f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2383f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2384f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2385f384594dSTobias Grosser         }
2386f384594dSTobias Grosser 
2387f384594dSTobias Grosser     return Accesses;
2388f384594dSTobias Grosser   }
2389f384594dSTobias Grosser 
2390f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2391f384594dSTobias Grosser   ///
2392f384594dSTobias Grosser   /// @see getTaggedAccesses
2393f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2394f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2395f384594dSTobias Grosser   }
2396f384594dSTobias Grosser 
2397f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2398f384594dSTobias Grosser   ///
2399f384594dSTobias Grosser   /// @see getTaggedAccesses
2400f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2401f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2402f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2403f384594dSTobias Grosser   }
2404f384594dSTobias Grosser 
2405f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2406f384594dSTobias Grosser   ///
2407f384594dSTobias Grosser   /// @see getTaggedAccesses
2408f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2409f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2410f384594dSTobias Grosser   }
2411f384594dSTobias Grosser 
2412aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2413aef5196fSTobias Grosser   ///
2414aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2415aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2416aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2417aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2418aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2419aef5196fSTobias Grosser   /// the data format that ppcg expects.
2420aef5196fSTobias Grosser   ///
2421aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2422aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2423aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2424bd81a7eeSTobias Grosser         S->getIslCtx(),
2425bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2426aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2427aef5196fSTobias Grosser 
242825271b91STobias Grosser     for (const SCEV *P : S->parameters()) {
242925271b91STobias Grosser       isl_id *Id = S->getIdForParam(P);
2430aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2431aef5196fSTobias Grosser     }
2432aef5196fSTobias Grosser 
2433aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
243477eef90fSTobias Grosser       auto Id = Array->getBasePtrId().release();
2435aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2436aef5196fSTobias Grosser     }
2437aef5196fSTobias Grosser 
2438aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2439aef5196fSTobias Grosser 
2440aef5196fSTobias Grosser     return Names;
2441aef5196fSTobias Grosser   }
2442aef5196fSTobias Grosser 
2443e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2444e938517eSTobias Grosser   ///
2445f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2446f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2447f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2448f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2449e938517eSTobias Grosser   ///
2450e938517eSTobias Grosser   /// @returns A new ppcg scop.
2451e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
24529e3db2b7SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
24539e3db2b7SSiddharth Bhat 
2454e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2455e938517eSTobias Grosser 
2456e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2457a82f2d26SSiddharth Bhat     // enable live range reordering
2458a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2459e938517eSTobias Grosser 
2460e938517eSTobias Grosser     PPCGScop->start = 0;
2461e938517eSTobias Grosser     PPCGScop->end = 0;
2462e938517eSTobias Grosser 
2463f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2464f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
24659e3db2b7SSiddharth Bhat     // TODO: investigate this further. PPCG calls collect_call_domains.
24669e3db2b7SSiddharth Bhat     PPCGScop->call = isl_union_set_from_set(S->getContext());
2467f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2468f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2469e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2470f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2471f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2472f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2473f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2474e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
24759e3db2b7SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
24769e3db2b7SSiddharth Bhat     PPCGScop->must_kills = KillsInfo.MustKills.take();
24779e3db2b7SSiddharth Bhat 
2478e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2479a82f2d26SSiddharth Bhat     PPCGScop->independence =
2480a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2481e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2482e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2483e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2484e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2485e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2486e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2487e938517eSTobias Grosser 
2488f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2489a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2490a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2491a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2492a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2493a82f2d26SSiddharth Bhat 
2494a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2495e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2496e938517eSTobias Grosser 
2497f384594dSTobias Grosser     compute_tagger(PPCGScop);
2498f384594dSTobias Grosser     compute_dependences(PPCGScop);
24999e3db2b7SSiddharth Bhat     eliminate_dead_code(PPCGScop);
2500f384594dSTobias Grosser 
2501e938517eSTobias Grosser     return PPCGScop;
2502e938517eSTobias Grosser   }
2503e938517eSTobias Grosser 
2504a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
250560f63b49STobias Grosser   ///
250660f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
250760f63b49STobias Grosser   ///
250860f63b49STobias Grosser   /// @returns A list of array accesses.
250960f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
251060f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
251160f63b49STobias Grosser 
251260f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
251360f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
251460f63b49STobias Grosser       Access->read = Acc->isRead();
251560f63b49STobias Grosser       Access->write = Acc->isWrite();
25161515f6b9STobias Grosser       Access->access = Acc->getAccessRelation().release();
251760f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
251860f63b49STobias Grosser       Space = isl_space_range(Space);
251960f63b49STobias Grosser       Space = isl_space_from_range(Space);
2520fe46c3ffSTobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
252160f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
252260f63b49STobias Grosser       Access->tagged_access =
25231515f6b9STobias Grosser           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2524b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
2525fe46c3ffSTobias Grosser       Access->ref_id = Acc->getId().release();
252660f63b49STobias Grosser       Access->next = Accesses;
2527b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
252860f63b49STobias Grosser       Accesses = Access;
252960f63b49STobias Grosser     }
253060f63b49STobias Grosser 
253160f63b49STobias Grosser     return Accesses;
253260f63b49STobias Grosser   }
253360f63b49STobias Grosser 
253469b46751STobias Grosser   /// Collect the list of GPU statements.
253569b46751STobias Grosser   ///
253669b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
253769b46751STobias Grosser   /// as well as a list with all memory accesses.
253869b46751STobias Grosser   ///
253969b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
254069b46751STobias Grosser   ///
254169b46751STobias Grosser   /// @returns A linked-list of statements.
254269b46751STobias Grosser   gpu_stmt *getStatements() {
254369b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
254469b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
254569b46751STobias Grosser 
254669b46751STobias Grosser     int i = 0;
254769b46751STobias Grosser     for (auto &Stmt : *S) {
254869b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
254969b46751STobias Grosser 
255069b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
255169b46751STobias Grosser 
255269b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
255369b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
255460f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
255569b46751STobias Grosser       i++;
255669b46751STobias Grosser     }
255769b46751STobias Grosser 
255869b46751STobias Grosser     return Stmts;
255969b46751STobias Grosser   }
256069b46751STobias Grosser 
256160f63b49STobias Grosser   /// Derive the extent of an array.
256260f63b49STobias Grosser   ///
2563d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2564d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2565d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2566d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2567d58acf86STobias Grosser   /// subscript value for the first dimension.
256860f63b49STobias Grosser   ///
256960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
257060f63b49STobias Grosser   ///
257160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
257260f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2573d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
257460f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
257560f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2576d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
257760f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2578d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2579d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2580d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2581d58acf86STobias Grosser 
2582d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2583d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
258477eef90fSTobias Grosser       return isl_set_empty(Array->getSpace().release());
2585d58acf86STobias Grosser     }
2586d58acf86STobias Grosser 
2587d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2588d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
258977eef90fSTobias Grosser       return isl_set_universe(Array->getSpace().release());
2590d58acf86STobias Grosser     }
2591d58acf86STobias Grosser 
259260f63b49STobias Grosser     isl_set *AccessSet =
259377eef90fSTobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace().release());
259460f63b49STobias Grosser 
2595d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
259677eef90fSTobias Grosser     isl_local_space *LS =
259777eef90fSTobias Grosser         isl_local_space_from_space(Array->getSpace().release());
2598d58acf86STobias Grosser 
2599d58acf86STobias Grosser     isl_pw_aff *Val =
2600d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2601d58acf86STobias Grosser 
2602d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2603d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2604d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2605d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2606d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2607d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
260877eef90fSTobias Grosser     OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in,
260977eef90fSTobias Grosser                                        Array->getBasePtrId().release());
261077eef90fSTobias Grosser     OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in,
261177eef90fSTobias Grosser                                        Array->getBasePtrId().release());
2612d58acf86STobias Grosser 
261377eef90fSTobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace().release());
2614d58acf86STobias Grosser 
2615d58acf86STobias Grosser     Extent = isl_set_intersect(
2616d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2617d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2618d58acf86STobias Grosser 
2619d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2620d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2621d58acf86STobias Grosser 
2622b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2623d58acf86STobias Grosser       isl_pw_aff *PwAff =
262477eef90fSTobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release());
2625b7f68b8cSSiddharth Bhat 
2626b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2627b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2628b7f68b8cSSiddharth Bhat       if (!PwAff) {
2629b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2630b7f68b8cSSiddharth Bhat         continue;
2631b7f68b8cSSiddharth Bhat       }
2632b7f68b8cSSiddharth Bhat 
2633d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
263477eef90fSTobias Grosser           isl_local_space_from_space(Array->getSpace().release()), isl_dim_set,
263577eef90fSTobias Grosser           i));
2636d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2637d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2638d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2639d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2640d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2641d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2642d58acf86STobias Grosser     }
2643d58acf86STobias Grosser 
2644d58acf86STobias Grosser     return Extent;
264560f63b49STobias Grosser   }
264660f63b49STobias Grosser 
264760f63b49STobias Grosser   /// Derive the bounds of an array.
264860f63b49STobias Grosser   ///
264960f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
265060f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
265160f63b49STobias Grosser   /// ScopArrayInfo.
265260f63b49STobias Grosser   ///
265360f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
265460f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
265560f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
26569e3db2b7SSiddharth Bhat     isl_pw_aff_list *BoundsList =
26579e3db2b7SSiddharth Bhat         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
26589e3db2b7SSiddharth Bhat     std::vector<isl::pw_aff> PwAffs;
26599e3db2b7SSiddharth Bhat 
26609e3db2b7SSiddharth Bhat     isl_space *AlignSpace = S->getParamSpace();
26619e3db2b7SSiddharth Bhat     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
26629e3db2b7SSiddharth Bhat 
266360f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
266402293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
266502293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
266602293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
266702293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
266802293ed7STobias Grosser         isl_set_free(Dom);
26699e3db2b7SSiddharth Bhat         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
26709e3db2b7SSiddharth Bhat         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
26719e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
26729e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
267302293ed7STobias Grosser       } else {
267460f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
267560f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
267660f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
267760f63b49STobias Grosser         isl_set_free(Dom);
267860f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
267902293ed7STobias Grosser         isl_local_space *LS =
268002293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
268160f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
268260f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
268360f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
268460f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
26859e3db2b7SSiddharth Bhat         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
26869e3db2b7SSiddharth Bhat         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
26879e3db2b7SSiddharth Bhat         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
268860f63b49STobias Grosser       }
268902293ed7STobias Grosser     }
269060f63b49STobias Grosser 
269160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
269277eef90fSTobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
269360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
269460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
269560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
26969e3db2b7SSiddharth Bhat       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
26979e3db2b7SSiddharth Bhat       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
26989e3db2b7SSiddharth Bhat       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
269960f63b49STobias Grosser     }
27009e3db2b7SSiddharth Bhat 
27019e3db2b7SSiddharth Bhat     isl_space_free(AlignSpace);
27029e3db2b7SSiddharth Bhat     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
27039e3db2b7SSiddharth Bhat 
27049e3db2b7SSiddharth Bhat     assert(BoundsSpace && "Unable to access space of array.");
27059e3db2b7SSiddharth Bhat     assert(BoundsList && "Unable to access list of bounds.");
27069e3db2b7SSiddharth Bhat 
27079e3db2b7SSiddharth Bhat     PPCGArray.bound =
27089e3db2b7SSiddharth Bhat         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
27099e3db2b7SSiddharth Bhat     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
271060f63b49STobias Grosser   }
271160f63b49STobias Grosser 
271260f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
271360f63b49STobias Grosser   ///
271460f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
271543f178bbSSiddharth Bhat   void createArrays(gpu_prog *PPCGProg,
271643f178bbSSiddharth Bhat                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
271760f63b49STobias Grosser     int i = 0;
271843f178bbSSiddharth Bhat     for (auto &Array : ValidSAIs) {
271960f63b49STobias Grosser       std::string TypeName;
272060f63b49STobias Grosser       raw_string_ostream OS(TypeName);
272160f63b49STobias Grosser 
272260f63b49STobias Grosser       OS << *Array->getElementType();
272360f63b49STobias Grosser       TypeName = OS.str();
272460f63b49STobias Grosser 
272560f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
272660f63b49STobias Grosser 
272777eef90fSTobias Grosser       PPCGArray.space = Array->getSpace().release();
272860f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
272960f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
273060f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
273160f63b49STobias Grosser       PPCGArray.extent = nullptr;
273260f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
273360f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
273460f63b49STobias Grosser       PPCGArray.n_ref = 0;
273560f63b49STobias Grosser       PPCGArray.refs = nullptr;
273660f63b49STobias Grosser       PPCGArray.accessed = true;
2737fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2738fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
273960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
274060f63b49STobias Grosser       PPCGArray.local = false;
274160f63b49STobias Grosser       PPCGArray.declare_local = false;
274260f63b49STobias Grosser       PPCGArray.global = false;
274360f63b49STobias Grosser       PPCGArray.linearize = false;
274460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
274513c78e4dSTobias Grosser       PPCGArray.user = Array;
274660f63b49STobias Grosser 
27479e3db2b7SSiddharth Bhat       PPCGArray.bound = nullptr;
274860f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
27492d010dafSTobias Grosser       i++;
2750b9fc860aSTobias Grosser 
2751b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
275260f63b49STobias Grosser     }
275360f63b49STobias Grosser   }
275460f63b49STobias Grosser 
275560f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
275660f63b49STobias Grosser   ///
275760f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
275860f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
275960f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
276060f63b49STobias Grosser 
2761d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
276277eef90fSTobias Grosser       isl_space *Space = Array->getSpace().release();
276360f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
276460f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
276560f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
276660f63b49STobias Grosser     }
276760f63b49STobias Grosser 
276860f63b49STobias Grosser     return Maps;
276960f63b49STobias Grosser   }
277060f63b49STobias Grosser 
2771e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2772e938517eSTobias Grosser   ///
2773a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2774e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2775e938517eSTobias Grosser 
2776e938517eSTobias Grosser     if (!PPCGScop)
2777e938517eSTobias Grosser       return nullptr;
2778e938517eSTobias Grosser 
2779e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2780e938517eSTobias Grosser 
2781e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2782e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2783aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
278460f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
278560f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
278660f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
278760f63b49STobias Grosser     PPCGProg->tagged_must_kill =
278860f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
278960f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
279060f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
27919e3db2b7SSiddharth Bhat     // TODO: verify that this assignment is correct.
2792e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2793a82f2d26SSiddharth Bhat 
2794a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2795a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2796a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2797a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2798a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2799a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
280069b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
280169b46751STobias Grosser     PPCGProg->stmts = getStatements();
280243f178bbSSiddharth Bhat 
280343f178bbSSiddharth Bhat     // Only consider arrays that have a non-empty extent.
280443f178bbSSiddharth Bhat     // Otherwise, this will cause us to consider the following kinds of
280543f178bbSSiddharth Bhat     // empty arrays:
280643f178bbSSiddharth Bhat     //     1. Invariant loads that are represented by SAI objects.
280743f178bbSSiddharth Bhat     //     2. Arrays with statically known zero size.
280843f178bbSSiddharth Bhat     auto ValidSAIsRange =
280943f178bbSSiddharth Bhat         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
281043f178bbSSiddharth Bhat           return !isl::manage(getExtent(SAI)).is_empty();
281143f178bbSSiddharth Bhat         });
281243f178bbSSiddharth Bhat     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
281343f178bbSSiddharth Bhat                                               ValidSAIsRange.end());
281443f178bbSSiddharth Bhat 
281543f178bbSSiddharth Bhat     PPCGProg->n_array =
281643f178bbSSiddharth Bhat         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
281760f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
281860f63b49STobias Grosser                                        PPCGProg->n_array);
281960f63b49STobias Grosser 
282043f178bbSSiddharth Bhat     createArrays(PPCGProg, ValidSAIs);
2821e938517eSTobias Grosser 
2822d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2823e938517eSTobias Grosser     return PPCGProg;
2824e938517eSTobias Grosser   }
2825e938517eSTobias Grosser 
282669b46751STobias Grosser   struct PrintGPUUserData {
282769b46751STobias Grosser     struct cuda_info *CudaInfo;
282869b46751STobias Grosser     struct gpu_prog *PPCGProg;
282969b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
283069b46751STobias Grosser   };
283169b46751STobias Grosser 
283269b46751STobias Grosser   /// Print a user statement node in the host code.
283369b46751STobias Grosser   ///
283469b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
283569b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
283669b46751STobias Grosser   /// host ast.
283769b46751STobias Grosser   ///
283869b46751STobias Grosser   /// @param P The printer to print to
283969b46751STobias Grosser   /// @param Options The printing options to use
284069b46751STobias Grosser   /// @param Node The node to print
284169b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
284269b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
284369b46751STobias Grosser   ///
284469b46751STobias Grosser   /// @returns A printer to which the output has been printed.
284569b46751STobias Grosser   static __isl_give isl_printer *
284669b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
284769b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
284869b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
284969b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
285069b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
285169b46751STobias Grosser 
285269b46751STobias Grosser     if (Id) {
285320251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
285420251734STobias Grosser 
285520251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
285620251734STobias Grosser       // otherwise try to call pet functionality that is not available in
285720251734STobias Grosser       // Polly.
285820251734STobias Grosser       if (IsUser) {
285920251734STobias Grosser         P = isl_printer_start_line(P);
286020251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
286120251734STobias Grosser         P = isl_printer_end_line(P);
286220251734STobias Grosser         isl_id_free(Id);
286320251734STobias Grosser         isl_ast_print_options_free(Options);
286420251734STobias Grosser         return P;
286520251734STobias Grosser       }
286620251734STobias Grosser 
286769b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
286869b46751STobias Grosser       isl_id_free(Id);
286969b46751STobias Grosser       Data->Kernels.push_back(Kernel);
287069b46751STobias Grosser     }
287169b46751STobias Grosser 
287269b46751STobias Grosser     return print_host_user(P, Options, Node, User);
287369b46751STobias Grosser   }
287469b46751STobias Grosser 
287569b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
287669b46751STobias Grosser   ///
287769b46751STobias Grosser   /// @param Kernel The kernel to print
287869b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
287969b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
288069b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
288169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
288269b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
288369b46751STobias Grosser     char *String = isl_printer_get_str(P);
288469b46751STobias Grosser     printf("%s\n", String);
288569b46751STobias Grosser     free(String);
288669b46751STobias Grosser     isl_printer_free(P);
288769b46751STobias Grosser   }
288869b46751STobias Grosser 
288969b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
289069b46751STobias Grosser   ///
289169b46751STobias Grosser   /// @param Tree An AST describing GPU code
289269b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
289369b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
289469b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
289569b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
289669b46751STobias Grosser 
289769b46751STobias Grosser     PrintGPUUserData Data;
289869b46751STobias Grosser     Data.PPCGProg = PPCGProg;
289969b46751STobias Grosser 
290069b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
290169b46751STobias Grosser     Options =
290269b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
290369b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
290469b46751STobias Grosser     char *String = isl_printer_get_str(P);
290569b46751STobias Grosser     printf("# host\n");
290669b46751STobias Grosser     printf("%s\n", String);
290769b46751STobias Grosser     free(String);
290869b46751STobias Grosser     isl_printer_free(P);
290969b46751STobias Grosser 
291069b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
291169b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
291269b46751STobias Grosser       printKernel(Kernel);
291369b46751STobias Grosser     }
291469b46751STobias Grosser   }
291569b46751STobias Grosser 
2916f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2917f384594dSTobias Grosser   //
2918f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2919f384594dSTobias Grosser   //
2920f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2921f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2922f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2923f384594dSTobias Grosser   //
2924f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2925f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2926f384594dSTobias Grosser   // strategy directly from this pass.
2927f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2928f384594dSTobias Grosser 
2929f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2930f384594dSTobias Grosser 
2931f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2932f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2933f384594dSTobias Grosser     PPCGGen->print = nullptr;
2934f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
293560c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2936f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2937f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2938f384594dSTobias Grosser     PPCGGen->types.n = 0;
2939f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2940f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2941f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2942f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2943f384594dSTobias Grosser 
2944f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2945f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2946f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
29472341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2948f384594dSTobias Grosser 
2949f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2950f384594dSTobias Grosser 
2951aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2952aef5196fSTobias Grosser 
295369b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2954aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
295569b46751STobias Grosser     } else {
2956aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
295769b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
295869b46751STobias Grosser     }
2959aef5196fSTobias Grosser 
2960f384594dSTobias Grosser     if (DumpSchedule) {
2961f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2962f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2963f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2964f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2965f384594dSTobias Grosser       if (Schedule)
2966f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2967f384594dSTobias Grosser       else
2968f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2969f384594dSTobias Grosser 
2970f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2971f384594dSTobias Grosser       isl_printer_free(P);
2972f384594dSTobias Grosser     }
2973f384594dSTobias Grosser 
297469b46751STobias Grosser     if (DumpCode) {
297569b46751STobias Grosser       printf("Code\n");
297669b46751STobias Grosser       printf("====\n");
297769b46751STobias Grosser       if (PPCGGen->tree)
297869b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
297969b46751STobias Grosser       else
298069b46751STobias Grosser         printf("No code generated\n");
298169b46751STobias Grosser     }
298269b46751STobias Grosser 
2983f384594dSTobias Grosser     isl_schedule_free(Schedule);
2984f384594dSTobias Grosser 
2985f384594dSTobias Grosser     return PPCGGen;
2986f384594dSTobias Grosser   }
2987f384594dSTobias Grosser 
2988f384594dSTobias Grosser   /// Free gpu_gen structure.
2989f384594dSTobias Grosser   ///
2990f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2991f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2992f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2993f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2994f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2995f384594dSTobias Grosser     free(PPCGGen);
2996f384594dSTobias Grosser   }
2997f384594dSTobias Grosser 
2998b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2999b307ed4dSTobias Grosser   ///
3000b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
3001b307ed4dSTobias Grosser   /// ourselves.
3002b307ed4dSTobias Grosser   ///
3003b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
3004b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
3005b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
3006b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
3007b307ed4dSTobias Grosser     free(PPCGScop->options);
3008b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
3009b307ed4dSTobias Grosser   }
3010b307ed4dSTobias Grosser 
301182f2af35STobias Grosser   /// Approximate the number of points in the set.
301282f2af35STobias Grosser   ///
301382f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
301482f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
301582f2af35STobias Grosser   ///
301682f2af35STobias Grosser   /// @param Set   The set to count.
301782f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
301882f2af35STobias Grosser   ///              expression.
301982f2af35STobias Grosser   ///
302082f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
302182f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
302282f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
302382f2af35STobias Grosser 
302482f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
302582f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
302682f2af35STobias Grosser 
302782f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
302882f2af35STobias Grosser     Space = isl_space_params(Space);
302982f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
303082f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
303182f2af35STobias Grosser 
303282f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
303382f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
303482f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
303582f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
303682f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
303782f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
303882f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
303982f2af35STobias Grosser     }
304082f2af35STobias Grosser 
304182f2af35STobias Grosser     isl_set_free(Set);
304282f2af35STobias Grosser     isl_pw_aff_free(OneAff);
304382f2af35STobias Grosser 
304482f2af35STobias Grosser     return Expr;
304582f2af35STobias Grosser   }
304682f2af35STobias Grosser 
304782f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
304882f2af35STobias Grosser   /// statement.
304982f2af35STobias Grosser   ///
305082f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
305182f2af35STobias Grosser   ///              instructions.
305282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
305382f2af35STobias Grosser   ///              expression.
305482f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
305582f2af35STobias Grosser   ///          by @p Stmt.
305682f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
305782f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
305882f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
305982f2af35STobias Grosser 
306082f2af35STobias Grosser     long InstCount = 0;
306182f2af35STobias Grosser 
306282f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
306382f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
306482f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
306582f2af35STobias Grosser     } else {
306682f2af35STobias Grosser       auto *R = Stmt.getRegion();
306782f2af35STobias Grosser 
306882f2af35STobias Grosser       for (auto *BB : R->blocks()) {
306982f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
307082f2af35STobias Grosser       }
307182f2af35STobias Grosser     }
307282f2af35STobias Grosser 
307382f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
307482f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
307582f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
307682f2af35STobias Grosser   }
307782f2af35STobias Grosser 
307882f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
307982f2af35STobias Grosser   ///
308082f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
308182f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
308282f2af35STobias Grosser   ///              expression.
308382f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
308482f2af35STobias Grosser   ///          in @p S.
308582f2af35STobias Grosser   __isl_give isl_ast_expr *
308682f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
308782f2af35STobias Grosser     isl_ast_expr *Instructions;
308882f2af35STobias Grosser 
308982f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
309082f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
309182f2af35STobias Grosser 
309282f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
309382f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
309482f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
309582f2af35STobias Grosser     }
309682f2af35STobias Grosser     return Instructions;
309782f2af35STobias Grosser   }
309882f2af35STobias Grosser 
309982f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
310082f2af35STobias Grosser   ///
310182f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
310282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
310382f2af35STobias Grosser   ///              expression.
310482f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
310582f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
310682f2af35STobias Grosser   __isl_give isl_ast_expr *
310782f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
310882f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
310982f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
311082f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
311182f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
311282f2af35STobias Grosser   }
311382f2af35STobias Grosser 
3114f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
3115f291c8d5SSiddharth Bhat   /// kernels.
3116f291c8d5SSiddharth Bhat   ///
3117f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
3118f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
3119018103d3STobias Grosser   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) {
3120f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
3121f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
3122f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
3123f291c8d5SSiddharth Bhat         continue;
3124f291c8d5SSiddharth Bhat       }
3125f291c8d5SSiddharth Bhat 
3126bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
3127bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
3128bccaea57SSiddharth Bhat         if (!p)
3129bccaea57SSiddharth Bhat           continue;
3130bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
3131bccaea57SSiddharth Bhat           return true;
3132bccaea57SSiddharth Bhat       }
3133f291c8d5SSiddharth Bhat     }
3134bccaea57SSiddharth Bhat     return false;
3135bccaea57SSiddharth Bhat   }
3136bccaea57SSiddharth Bhat 
3137f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
3138f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
3139bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
3140bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
3141018103d3STobias Grosser         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock()))
3142bccaea57SSiddharth Bhat           return true;
3143bccaea57SSiddharth Bhat       } else {
3144bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
3145bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
3146bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
3147018103d3STobias Grosser           if (containsInvalidKernelFunctionInBlock(BB))
3148bccaea57SSiddharth Bhat             return true;
3149bccaea57SSiddharth Bhat       }
3150bccaea57SSiddharth Bhat     }
3151bccaea57SSiddharth Bhat     return false;
3152bccaea57SSiddharth Bhat   }
3153bccaea57SSiddharth Bhat 
315438fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
315538fc0aedSTobias Grosser   ///
315632837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
315732837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
315832837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
315938fc0aedSTobias Grosser     ScopAnnotator Annotator;
316038fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
316138fc0aedSTobias Grosser 
316238fc0aedSTobias Grosser     Region *R = &S->getRegion();
316338fc0aedSTobias Grosser 
316438fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
316538fc0aedSTobias Grosser 
316638fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
316738fc0aedSTobias Grosser 
316838fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
316938fc0aedSTobias Grosser 
317038fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
317138fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
317238fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
317338fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
317438fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
317538fc0aedSTobias Grosser     // code generating this scop.
317603346c27SSiddharth Bhat     BBPair StartExitBlocks;
317703346c27SSiddharth Bhat     BranchInst *CondBr = nullptr;
317803346c27SSiddharth Bhat     std::tie(StartExitBlocks, CondBr) =
31792d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3180256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
318138fc0aedSTobias Grosser 
318203346c27SSiddharth Bhat     assert(CondBr && "CondBr not initialized by executeScopConditionally");
318303346c27SSiddharth Bhat 
31842d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
318517f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
3186acf80064SEli Friedman 
318738fc0aedSTobias Grosser     // TODO: Handle LICM
318838fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
318938fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
319038fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
3191cb1aef8dSTobias Grosser 
3192cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
31932b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
319482f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
319582f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3196cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
3197cb1aef8dSTobias Grosser 
31989e3db2b7SSiddharth Bhat     // preload invariant loads. Note: This should happen before the RTC
31999e3db2b7SSiddharth Bhat     // because the RTC may depend on values that are invariant load hoisted.
3200*4ebeb356SSiddharth Bhat     if (!NodeBuilder.preloadInvariantLoads())
3201*4ebeb356SSiddharth Bhat       report_fatal_error("preloading invariant loads failed in function: " +
3202*4ebeb356SSiddharth Bhat                          S->getFunction().getName() +
3203*4ebeb356SSiddharth Bhat                          " | Scop Region: " + S->getNameStr());
32049e3db2b7SSiddharth Bhat 
3205cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
3206cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3207cb1aef8dSTobias Grosser 
320838fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
3209fa7b0802STobias Grosser 
321038fc0aedSTobias Grosser     NodeBuilder.create(Root);
32115857b701STobias Grosser 
3212bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
3213bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3214de244eb4STobias Grosser     /// point in running it on a GPU.
3215bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
321603346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
3217bc653f20STobias Grosser 
32185857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
321903346c27SSiddharth Bhat       CondBr->setOperand(0, Builder.getFalse());
322038fc0aedSTobias Grosser   }
322138fc0aedSTobias Grosser 
3222e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
3223e938517eSTobias Grosser     S = &CurrentScop;
322438fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
322538fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
322638fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
32277b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
322838fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3229e938517eSTobias Grosser 
3230f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
3231f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
3232f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
3233bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
3234bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
3235f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
3236f291c8d5SSiddharth Bhat       DEBUG(
3237f291c8d5SSiddharth Bhat           dbgs()
3238f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
3239f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
3240bccaea57SSiddharth Bhat       return false;
3241f291c8d5SSiddharth Bhat     }
3242bccaea57SSiddharth Bhat 
3243e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
3244e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
3245f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
324638fc0aedSTobias Grosser 
324702ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
324832837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
324902ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
325002ca346eSSingapuram Sanjay Srivallabh     }
325138fc0aedSTobias Grosser 
3252b307ed4dSTobias Grosser     freeOptions(PPCGScop);
3253f384594dSTobias Grosser     freePPCGGen(PPCGGen);
3254e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
3255e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
3256e938517eSTobias Grosser 
3257e938517eSTobias Grosser     return true;
3258e938517eSTobias Grosser   }
32599dfe4e7cSTobias Grosser 
32609dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
32619dfe4e7cSTobias Grosser 
32629dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
32639dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
32649dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
32659dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
32665cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
32679dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
32689dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
32699dfe4e7cSTobias Grosser 
32709dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
32719dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
32729dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
32739dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
32749dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
32755cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
32769dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
32779dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
32789dfe4e7cSTobias Grosser 
32799dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
32809dfe4e7cSTobias Grosser     //        region tree.
32819dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
32829dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
32839dfe4e7cSTobias Grosser   }
32849dfe4e7cSTobias Grosser };
328524222c73STobias Grosser } // namespace
32869dfe4e7cSTobias Grosser 
32879dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
32889dfe4e7cSTobias Grosser 
328917f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
329017f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
329117f01968SSiddharth Bhat   generator->Runtime = Runtime;
329217f01968SSiddharth Bhat   generator->Architecture = Arch;
329317f01968SSiddharth Bhat   return generator;
329417f01968SSiddharth Bhat }
32959dfe4e7cSTobias Grosser 
32969dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
32979dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
32989dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
32999dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
33009dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
33019dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
33029dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
33035cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
33049dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
33059dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3306