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   ///
132a82f2d26SSiddharth Bhat   /// We currently only derive kill information for phi nodes, as phi nodes
133a82f2d26SSiddharth Bhat   /// allow us to easily derive kill information. PHI nodes are not alive
134a82f2d26SSiddharth Bhat   /// outside the scop and can consequently all be "killed". [params] -> {
135a82f2d26SSiddharth Bhat   /// [Stmt_phantom[] -> ref_phantom[]] -> phi_ref[] }
136a82f2d26SSiddharth Bhat   isl::union_map TaggedMustKills;
137a82f2d26SSiddharth Bhat 
138a82f2d26SSiddharth Bhat   MustKillsInfo() : KillsSchedule(nullptr), TaggedMustKills(nullptr){};
139a82f2d26SSiddharth Bhat };
140a82f2d26SSiddharth Bhat 
141761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S.
142761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data
143761e5b93SSiddharth Bhat /// can flow in/out of the value any more.
144761e5b93SSiddharth Bhat /// @see computeMustKillsInfo
145761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S,
146761e5b93SSiddharth Bhat                                         const ScopArrayInfo *SAI) {
147761e5b93SSiddharth Bhat   assert(SAI->isValueKind() && "this function only deals with scalars."
148761e5b93SSiddharth Bhat                                " Dealing with arrays required alias analysis");
149761e5b93SSiddharth Bhat 
150761e5b93SSiddharth Bhat   const Region &R = S.getRegion();
151761e5b93SSiddharth Bhat   for (User *U : SAI->getBasePtr()->users()) {
152761e5b93SSiddharth Bhat     Instruction *I = dyn_cast<Instruction>(U);
153761e5b93SSiddharth Bhat     assert(I && "invalid user of scop array info");
154761e5b93SSiddharth Bhat     if (!R.contains(I))
155761e5b93SSiddharth Bhat       return false;
156761e5b93SSiddharth Bhat   }
157761e5b93SSiddharth Bhat   return true;
158761e5b93SSiddharth Bhat }
159761e5b93SSiddharth Bhat 
160a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG.
161a82f2d26SSiddharth Bhat ///
162a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information
163a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup
164a82f2d26SSiddharth Bhat /// PPCG.
165a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) {
166a82f2d26SSiddharth Bhat   const isl::space ParamSpace(isl::manage(S.getParamSpace()));
167a82f2d26SSiddharth Bhat   MustKillsInfo Info;
168a82f2d26SSiddharth Bhat 
169761e5b93SSiddharth Bhat   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
170761e5b93SSiddharth Bhat   //      1.1 phi nodes in scop.
171761e5b93SSiddharth Bhat   //      1.2 scalars that are only used within the scop
172a82f2d26SSiddharth Bhat   SmallVector<isl::id, 4> KillMemIds;
173a82f2d26SSiddharth Bhat   for (ScopArrayInfo *SAI : S.arrays()) {
174761e5b93SSiddharth Bhat     if (SAI->isPHIKind() ||
175761e5b93SSiddharth Bhat         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
176a82f2d26SSiddharth Bhat       KillMemIds.push_back(isl::manage(SAI->getBasePtrId()));
177a82f2d26SSiddharth Bhat   }
178a82f2d26SSiddharth Bhat 
179a82f2d26SSiddharth Bhat   Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace));
180a82f2d26SSiddharth Bhat 
181a82f2d26SSiddharth Bhat   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
182a82f2d26SSiddharth Bhat   // schedule:
183a82f2d26SSiddharth Bhat   //     - filter: "[control] -> { }"
184a82f2d26SSiddharth Bhat   // So, we choose to not create this to keep the output a little nicer,
185a82f2d26SSiddharth Bhat   // at the cost of some code complexity.
186a82f2d26SSiddharth Bhat   Info.KillsSchedule = nullptr;
187a82f2d26SSiddharth Bhat 
188a82f2d26SSiddharth Bhat   for (isl::id &phiId : KillMemIds) {
189a82f2d26SSiddharth Bhat     isl::id KillStmtId = isl::id::alloc(
190a82f2d26SSiddharth Bhat         S.getIslCtx(), std::string("SKill_phantom_").append(phiId.get_name()),
191a82f2d26SSiddharth Bhat         nullptr);
192a82f2d26SSiddharth Bhat 
193a82f2d26SSiddharth Bhat     // NOTE: construction of tagged_must_kill:
194a82f2d26SSiddharth Bhat     // 2. We need to construct a map:
195a82f2d26SSiddharth Bhat     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> phi_ref }
196a82f2d26SSiddharth Bhat     // To construct this, we use `isl_map_domain_product` on 2 maps`:
197a82f2d26SSiddharth Bhat     // 2a. StmtToPhi:
198a82f2d26SSiddharth Bhat     //         [param] -> { Stmt_phantom[] -> phi_ref[] }
199a82f2d26SSiddharth Bhat     // 2b. PhantomRefToPhi:
200a82f2d26SSiddharth Bhat     //         [param] -> { ref_phantom[] -> phi_ref[] }
201a82f2d26SSiddharth Bhat     //
202a82f2d26SSiddharth Bhat     // Combining these with `isl_map_domain_product` gives us
203a82f2d26SSiddharth Bhat     // TaggedMustKill:
204a82f2d26SSiddharth Bhat     //     [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] }
205a82f2d26SSiddharth Bhat 
206a82f2d26SSiddharth Bhat     // 2a. [param] -> { S_2[] -> phi_ref[] }
207a82f2d26SSiddharth Bhat     isl::map StmtToPhi = isl::map::universe(isl::space(ParamSpace));
208a82f2d26SSiddharth Bhat     StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
209a82f2d26SSiddharth Bhat     StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::out, isl::id(phiId));
210a82f2d26SSiddharth Bhat 
211a82f2d26SSiddharth Bhat     isl::id PhantomRefId = isl::id::alloc(
212a82f2d26SSiddharth Bhat         S.getIslCtx(), std::string("ref_phantom") + phiId.get_name(), nullptr);
213a82f2d26SSiddharth Bhat 
214a82f2d26SSiddharth Bhat     // 2b. [param] -> { phantom_ref[] -> memref[] }
215a82f2d26SSiddharth Bhat     isl::map PhantomRefToPhi = isl::map::universe(isl::space(ParamSpace));
216a82f2d26SSiddharth Bhat     PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::in, PhantomRefId);
217a82f2d26SSiddharth Bhat     PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::out, phiId);
218a82f2d26SSiddharth Bhat 
219a82f2d26SSiddharth Bhat     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] }
220a82f2d26SSiddharth Bhat     isl::map TaggedMustKill = StmtToPhi.domain_product(PhantomRefToPhi);
221a82f2d26SSiddharth Bhat     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
222a82f2d26SSiddharth Bhat 
223a82f2d26SSiddharth Bhat     // 3. Create the kill schedule of the form:
224a82f2d26SSiddharth Bhat     //     "[param] -> { Stmt_phantom[] }"
225a82f2d26SSiddharth Bhat     // Then add this to Info.KillsSchedule.
226a82f2d26SSiddharth Bhat     isl::space KillStmtSpace = ParamSpace;
227a82f2d26SSiddharth Bhat     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
228a82f2d26SSiddharth Bhat     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
229a82f2d26SSiddharth Bhat 
230a82f2d26SSiddharth Bhat     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
231a82f2d26SSiddharth Bhat     if (Info.KillsSchedule)
232a82f2d26SSiddharth Bhat       Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule);
233a82f2d26SSiddharth Bhat     else
234a82f2d26SSiddharth Bhat       Info.KillsSchedule = KillSchedule;
235a82f2d26SSiddharth Bhat   }
236a82f2d26SSiddharth Bhat 
237a82f2d26SSiddharth Bhat   return Info;
238a82f2d26SSiddharth Bhat }
239a82f2d26SSiddharth Bhat 
24060c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
24160c60025STobias Grosser ///
24260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
24360c60025STobias Grosser /// of the scheduled ScopStmts.
24460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
245edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
24660c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
24760c60025STobias Grosser                                        isl_id *Id, void *User),
24860c60025STobias Grosser     void *UserIndex,
24960c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
250edb885cbSTobias Grosser     void *UserExpr) {
25160c60025STobias Grosser 
252edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
25360c60025STobias Grosser 
254edb885cbSTobias Grosser   isl_ctx *Ctx;
255edb885cbSTobias Grosser 
256edb885cbSTobias Grosser   if (!Stmt || !Build)
257edb885cbSTobias Grosser     return NULL;
258edb885cbSTobias Grosser 
259edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
260edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
261edb885cbSTobias Grosser 
262edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
263edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
264edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
265edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
266edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
267edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
268edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
269edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
270edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
271edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
272edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
273edb885cbSTobias Grosser   }
274edb885cbSTobias Grosser 
275edb885cbSTobias Grosser   return RefToExpr;
27660c60025STobias Grosser }
277f384594dSTobias Grosser 
278a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes,
279a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) {
280a90be207SSiddharth Bhat   int bytes = T->getPrimitiveSizeInBits() / 8;
281a90be207SSiddharth Bhat   if (bytes == 0)
282a90be207SSiddharth Bhat     bytes = T->getScalarSizeInBits() / 8;
283a90be207SSiddharth Bhat   return bytes;
284a90be207SSiddharth Bhat }
285a90be207SSiddharth Bhat 
28638fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
28738fc0aedSTobias Grosser ///
28838fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
289a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality
29038fc0aedSTobias Grosser /// for generating GPU specific user nodes.
29138fc0aedSTobias Grosser ///
29238fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
29338fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
29438fc0aedSTobias Grosser public:
2952d950f36SPhilip Pfaffe   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
29638fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
297acf80064SEli Friedman                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
29817f01968SSiddharth Bhat                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
2992d950f36SPhilip Pfaffe       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
30017f01968SSiddharth Bhat         Prog(Prog), Runtime(Runtime), Arch(Arch) {
301edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
302edb885cbSTobias Grosser   }
30338fc0aedSTobias Grosser 
304fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
305fa7b0802STobias Grosser   void initializeAfterRTH();
306fa7b0802STobias Grosser 
307fa7b0802STobias Grosser   /// Finalize the generated scop.
308fa7b0802STobias Grosser   virtual void finalize();
309fa7b0802STobias Grosser 
3105857b701STobias Grosser   /// Track if the full build process was successful.
3115857b701STobias Grosser   ///
3125857b701STobias Grosser   /// This value is set to false, if throughout the build process an error
3135857b701STobias Grosser   /// occurred which prevents us from generating valid GPU code.
3145857b701STobias Grosser   bool BuildSuccessful = true;
3155857b701STobias Grosser 
316bc653f20STobias Grosser   /// The maximal number of loops surrounding a sequential kernel.
317bc653f20STobias Grosser   unsigned DeepestSequential = 0;
318bc653f20STobias Grosser 
319bc653f20STobias Grosser   /// The maximal number of loops surrounding a parallel kernel.
320bc653f20STobias Grosser   unsigned DeepestParallel = 0;
321bc653f20STobias Grosser 
32279f13b9aSSingapuram Sanjay Srivallabh   /// Return the name to set for the ptx_kernel.
32379f13b9aSSingapuram Sanjay Srivallabh   std::string getKernelFuncName(int Kernel_id);
32479f13b9aSSingapuram Sanjay Srivallabh 
32538fc0aedSTobias Grosser private:
32674dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
32774dc3cb4STobias Grosser   ///
32874dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
32974dc3cb4STobias Grosser   /// more.
33074dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
33174dc3cb4STobias Grosser 
33213c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
33313c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
3347287aeddSTobias Grosser 
335fa7b0802STobias Grosser   /// The current GPU context.
336fa7b0802STobias Grosser   Value *GPUContext;
337fa7b0802STobias Grosser 
338b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
339b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
340b513b491STobias Grosser 
34132837fe3STobias Grosser   /// A module containing GPU code.
34232837fe3STobias Grosser   ///
34332837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
34432837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
34532837fe3STobias Grosser 
34632837fe3STobias Grosser   /// The GPU program we generate code for.
34732837fe3STobias Grosser   gpu_prog *Prog;
34832837fe3STobias Grosser 
34917f01968SSiddharth Bhat   /// The GPU Runtime implementation to use (OpenCL or CUDA).
35017f01968SSiddharth Bhat   GPURuntime Runtime;
35117f01968SSiddharth Bhat 
35217f01968SSiddharth Bhat   /// The GPU Architecture to target.
35317f01968SSiddharth Bhat   GPUArch Arch;
35417f01968SSiddharth Bhat 
355472f9654STobias Grosser   /// Class to free isl_ids.
356472f9654STobias Grosser   class IslIdDeleter {
357472f9654STobias Grosser   public:
358472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
359472f9654STobias Grosser   };
360472f9654STobias Grosser 
361472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
362472f9654STobias Grosser   ///
363472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
364472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
365472f9654STobias Grosser 
366edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
367edb885cbSTobias Grosser 
36838fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
36938fc0aedSTobias Grosser   ///
37038fc0aedSTobias Grosser   /// These AST nodes can be of type:
37138fc0aedSTobias Grosser   ///
37238fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
37338fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
37413c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
3755260c041STobias Grosser   ///   - In-kernel synchronization
3765260c041STobias Grosser   ///   - In-kernel memory copy statement
37738fc0aedSTobias Grosser   ///
3781fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
3791fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
38032837fe3STobias Grosser 
38113c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
38213c78e4dSTobias Grosser 
38313c78e4dSTobias Grosser   /// Create code for a data transfer statement
38413c78e4dSTobias Grosser   ///
38513c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
38613c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
38713c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
38813c78e4dSTobias Grosser                           enum DataDirection Direction);
38913c78e4dSTobias Grosser 
390edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
391edb885cbSTobias Grosser   ///
392edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
393edb885cbSTobias Grosser   ///
394f291c8d5SSiddharth Bhat   /// @returns A pair, whose first element contains the set of values
395f291c8d5SSiddharth Bhat   ///          referenced by the kernel, and whose second element contains the
396f291c8d5SSiddharth Bhat   ///          set of functions referenced by the kernel. All functions in the
397f291c8d5SSiddharth Bhat   ///          second set satisfy isValidFunctionInKernel.
398f291c8d5SSiddharth Bhat   std::pair<SetVector<Value *>, SetVector<Function *>>
399f291c8d5SSiddharth Bhat   getReferencesInKernel(ppcg_kernel *Kernel);
400edb885cbSTobias Grosser 
40179a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
40279a947c2STobias Grosser   ///
40379a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
40479a947c2STobias Grosser   ///
40579a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
40679a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
40779a947c2STobias Grosser 
408abed4969SSiddharth Bhat   /// Creates a array that can be sent to the kernel on the device using a
409abed4969SSiddharth Bhat   /// host pointer. This is required for managed memory, when we directly send
410abed4969SSiddharth Bhat   /// host pointers to the device.
411abed4969SSiddharth Bhat   /// \note
412abed4969SSiddharth Bhat   /// This is to be used only with managed memory
413abed4969SSiddharth Bhat   Value *getOrCreateManagedDeviceArray(gpu_array_info *Array,
414abed4969SSiddharth Bhat                                        ScopArrayInfo *ArrayInfo);
415abed4969SSiddharth Bhat 
41679a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
41779a947c2STobias Grosser   ///
41879a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
41979a947c2STobias Grosser   ///
42079a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
42179a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
42279a947c2STobias Grosser 
423a90be207SSiddharth Bhat   /// Store a specific kernel launch parameter in the array of kernel launch
424a90be207SSiddharth Bhat   /// parameters.
425a90be207SSiddharth Bhat   ///
426a90be207SSiddharth Bhat   /// @param Parameters The list of parameters in which to store.
427a90be207SSiddharth Bhat   /// @param Param      The kernel launch parameter to store.
428a90be207SSiddharth Bhat   /// @param Index      The index in the parameter list, at which to store the
429a90be207SSiddharth Bhat   ///                   parameter.
430a90be207SSiddharth Bhat   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
431a90be207SSiddharth Bhat                             int Index);
432a90be207SSiddharth Bhat 
43379a947c2STobias Grosser   /// Create kernel launch parameters.
43479a947c2STobias Grosser   ///
43579a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
43679a947c2STobias Grosser   /// @param F             The kernel function that has been created.
43757693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
43879a947c2STobias Grosser   ///
43979a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
44079a947c2STobias Grosser   ///          values that are passed to the kernel.
44157693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
44257693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
44379a947c2STobias Grosser 
444b513b491STobias Grosser   /// Create declarations for kernel variable.
445b513b491STobias Grosser   ///
446b513b491STobias Grosser   /// This includes shared memory declarations.
447b513b491STobias Grosser   ///
448b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
449b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
450b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
451b513b491STobias Grosser 
452c1c6a2a6STobias Grosser   /// Add CUDA annotations to module.
453c1c6a2a6STobias Grosser   ///
454c1c6a2a6STobias Grosser   /// Add a set of CUDA annotations that declares the maximal block dimensions
455c1c6a2a6STobias Grosser   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
456c1c6a2a6STobias Grosser   /// PTX compiler to bound the number of allocated registers to ensure the
457c1c6a2a6STobias Grosser   /// resulting kernel is known to run with up to as many block dimensions
458c1c6a2a6STobias Grosser   /// as specified here.
459c1c6a2a6STobias Grosser   ///
460c1c6a2a6STobias Grosser   /// @param M         The module to add the annotations to.
461c1c6a2a6STobias Grosser   /// @param BlockDimX The size of block dimension X.
462c1c6a2a6STobias Grosser   /// @param BlockDimY The size of block dimension Y.
463c1c6a2a6STobias Grosser   /// @param BlockDimZ The size of block dimension Z.
464c1c6a2a6STobias Grosser   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
465c1c6a2a6STobias Grosser                           Value *BlockDimZ);
466c1c6a2a6STobias Grosser 
46732837fe3STobias Grosser   /// Create GPU kernel.
46832837fe3STobias Grosser   ///
46932837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
47032837fe3STobias Grosser   ///
47132837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
47232837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
47332837fe3STobias Grosser 
47413c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
47513c78e4dSTobias Grosser   ///
47613c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
47713c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
47813c78e4dSTobias Grosser 
479aaabbbf8STobias Grosser   /// Generate code to compute the minimal offset at which an array is accessed.
480aaabbbf8STobias Grosser   ///
481aaabbbf8STobias Grosser   /// The offset of an array is the minimal array location accessed in a scop.
482aaabbbf8STobias Grosser   ///
483aaabbbf8STobias Grosser   /// Example:
484aaabbbf8STobias Grosser   ///
485aaabbbf8STobias Grosser   ///   for (long i = 0; i < 100; i++)
486aaabbbf8STobias Grosser   ///     A[i + 42] += ...
487aaabbbf8STobias Grosser   ///
488aaabbbf8STobias Grosser   ///   getArrayOffset(A) results in 42.
489aaabbbf8STobias Grosser   ///
490aaabbbf8STobias Grosser   /// @param Array The array for which to compute the offset.
491aaabbbf8STobias Grosser   /// @returns An llvm::Value that contains the offset of the array.
492aaabbbf8STobias Grosser   Value *getArrayOffset(gpu_array_info *Array);
493aaabbbf8STobias Grosser 
49400bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
49500bb5a99STobias Grosser   ///
49600bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
49700bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
49800bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
49900bb5a99STobias Grosser 
50032837fe3STobias Grosser   /// Create kernel function.
50132837fe3STobias Grosser   ///
50232837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
50332837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
50432837fe3STobias Grosser   /// start block of this newly created function.
50532837fe3STobias Grosser   ///
50632837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
507edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
508f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
509f291c8d5SSiddharth Bhat   ///                         kernel.
510edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
511f291c8d5SSiddharth Bhat                             SetVector<Value *> &SubtreeValues,
512f291c8d5SSiddharth Bhat                             SetVector<Function *> &SubtreeFunctions);
51332837fe3STobias Grosser 
51432837fe3STobias Grosser   /// Create the declaration of a kernel function.
51532837fe3STobias Grosser   ///
51632837fe3STobias Grosser   /// The kernel function takes as arguments:
51732837fe3STobias Grosser   ///
51832837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
519f6044bd0STobias Grosser   ///   - Host iterators
520c84a1995STobias Grosser   ///   - Parameters
52132837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
52232837fe3STobias Grosser   ///
52332837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
524edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
525edb885cbSTobias Grosser   ///
52632837fe3STobias Grosser   /// @returns The newly declared function.
527edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
528edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
52932837fe3STobias Grosser 
530472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
531472f9654STobias Grosser   ///
532472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
533472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
534472f9654STobias Grosser 
535f291c8d5SSiddharth Bhat   /// Setup the creation of functions referenced by the GPU kernel.
536f291c8d5SSiddharth Bhat   ///
537f291c8d5SSiddharth Bhat   /// 1. Create new function declarations in GPUModule which are the same as
538f291c8d5SSiddharth Bhat   /// SubtreeFunctions.
539f291c8d5SSiddharth Bhat   ///
540f291c8d5SSiddharth Bhat   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
541f291c8d5SSiddharth Bhat   /// old functions (that come from the original module) to new functions
542f291c8d5SSiddharth Bhat   /// (that are created within GPUModule). That way, we generate references
543f291c8d5SSiddharth Bhat   /// to the correct function (in GPUModule) in BlockGenerator.
544f291c8d5SSiddharth Bhat   ///
545f291c8d5SSiddharth Bhat   /// @see IslNodeBuilder::ValueMap
546f291c8d5SSiddharth Bhat   /// @see BlockGenerator::GlobalMap
547f291c8d5SSiddharth Bhat   /// @see BlockGenerator::getNewValue
548f291c8d5SSiddharth Bhat   /// @see GPUNodeBuilder::getReferencesInKernel.
549f291c8d5SSiddharth Bhat   ///
550f291c8d5SSiddharth Bhat   /// @param SubtreeFunctions The set of llvm::Functions referenced by
551f291c8d5SSiddharth Bhat   ///                         this kernel.
552f291c8d5SSiddharth Bhat   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
553f291c8d5SSiddharth Bhat 
554b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
555b513b491STobias Grosser   ///
556b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
557b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
558b513b491STobias Grosser 
559edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
560edb885cbSTobias Grosser   ///
561edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
562edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
563edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
564edb885cbSTobias Grosser 
5655260c041STobias Grosser   /// Create an in-kernel synchronization call.
5665260c041STobias Grosser   void createKernelSync();
5675260c041STobias Grosser 
56874dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
56974dc3cb4STobias Grosser   ///
57074dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
57174dc3cb4STobias Grosser   std::string createKernelASM();
57274dc3cb4STobias Grosser 
57374dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
57474dc3cb4STobias Grosser   ///
57574dc3cb4STobias Grosser   /// @param F The function to remove references to.
57674dc3cb4STobias Grosser   void clearDominators(Function *F);
57774dc3cb4STobias Grosser 
57874dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
57974dc3cb4STobias Grosser   ///
58074dc3cb4STobias Grosser   /// @param F The function to remove references to.
58174dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
58274dc3cb4STobias Grosser 
58374dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
58474dc3cb4STobias Grosser   ///
58574dc3cb4STobias Grosser   /// @param F The function to remove references to.
58674dc3cb4STobias Grosser   void clearLoops(Function *F);
58774dc3cb4STobias Grosser 
58832837fe3STobias Grosser   /// Finalize the generation of the kernel function.
58932837fe3STobias Grosser   ///
59032837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
59132837fe3STobias Grosser   /// dump its IR to stderr.
59257793596STobias Grosser   ///
59357793596STobias Grosser   /// @returns The Assembly string of the kernel.
59457793596STobias Grosser   std::string finalizeKernelFunction();
595fa7b0802STobias Grosser 
59651dfc275STobias Grosser   /// Finalize the generation of the kernel arguments.
59751dfc275STobias Grosser   ///
59851dfc275STobias Grosser   /// This function ensures that not-read-only scalars used in a kernel are
599a6d48f59SMichael Kruse   /// stored back to the global memory location they are backed with before
60051dfc275STobias Grosser   /// the kernel terminates.
60151dfc275STobias Grosser   ///
60251dfc275STobias Grosser   /// @params Kernel The kernel to finalize kernel arguments for.
60351dfc275STobias Grosser   void finalizeKernelArguments(ppcg_kernel *Kernel);
60451dfc275STobias Grosser 
6057287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
606fa7b0802STobias Grosser   void allocateDeviceArrays();
607fa7b0802STobias Grosser 
6087287aeddSTobias Grosser   /// Free all allocated device arrays.
6097287aeddSTobias Grosser   void freeDeviceArrays();
6107287aeddSTobias Grosser 
611fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
612fa7b0802STobias Grosser   ///
613fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
614fa7b0802STobias Grosser   Value *createCallInitContext();
615fa7b0802STobias Grosser 
61679a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
61779a947c2STobias Grosser   ///
61879a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
61979a947c2STobias Grosser   ///
62079a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
62179a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
62279a947c2STobias Grosser 
623fa7b0802STobias Grosser   /// Create a call to free the GPU context.
624fa7b0802STobias Grosser   ///
625fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
626fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
627fa7b0802STobias Grosser 
6287287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
6297287aeddSTobias Grosser   ///
6307287aeddSTobias Grosser   /// @param Size The size of memory to allocate
6317287aeddSTobias Grosser   ///
6327287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
633fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
6347287aeddSTobias Grosser 
6357287aeddSTobias Grosser   /// Create a call to free a device array.
6367287aeddSTobias Grosser   ///
6377287aeddSTobias Grosser   /// @param Array The device array to free.
6387287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
63913c78e4dSTobias Grosser 
64013c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
64113c78e4dSTobias Grosser   ///
64213c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
64313c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
64413c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
64513c78e4dSTobias Grosser                                       Value *Size);
64613c78e4dSTobias Grosser 
64713c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
64813c78e4dSTobias Grosser   ///
64913c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
65013c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
65113c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
65213c78e4dSTobias Grosser                                       Value *Size);
65357793596STobias Grosser 
654abed4969SSiddharth Bhat   /// Create a call to synchronize Host & Device.
655abed4969SSiddharth Bhat   /// \note
656abed4969SSiddharth Bhat   /// This is to be used only with managed memory.
657abed4969SSiddharth Bhat   void createCallSynchronizeDevice();
658abed4969SSiddharth Bhat 
65957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
66057793596STobias Grosser   ///
66157793596STobias Grosser   /// @param Buffer The string describing the kernel.
66257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
66357793596STobias Grosser   ///
66457793596STobias Grosser   /// @returns A pointer to a kernel object
66557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
66657793596STobias Grosser 
66757793596STobias Grosser   /// Create a call to free a GPU kernel.
66857793596STobias Grosser   ///
66957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
67057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
67179a947c2STobias Grosser 
67279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
67379a947c2STobias Grosser   ///
67479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
67579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
67679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
67779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
67879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
67979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
680a6d48f59SMichael Kruse   /// @param Parameters A pointer to an array that contains itself pointers to
68179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
68279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
68379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
68479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
68579a947c2STobias Grosser                               Value *Parameters);
6861fb9b64dSTobias Grosser };
6871fb9b64dSTobias Grosser 
68879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
689*1abd9ffaSSingapuram Sanjay Srivallabh   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
690*1abd9ffaSSingapuram Sanjay Srivallabh          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
69179f13b9aSSingapuram Sanjay Srivallabh }
69279f13b9aSSingapuram Sanjay Srivallabh 
693fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
694750160e2STobias Grosser   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
695750160e2STobias Grosser                                  &*Builder.GetInsertPoint(), &DT, &LI);
696750160e2STobias Grosser   NewBB->setName("polly.acc.initialize");
697750160e2STobias Grosser   Builder.SetInsertPoint(&NewBB->front());
698750160e2STobias Grosser 
699fa7b0802STobias Grosser   GPUContext = createCallInitContext();
700abed4969SSiddharth Bhat 
701abed4969SSiddharth Bhat   if (!ManagedMemory)
702fa7b0802STobias Grosser     allocateDeviceArrays();
703fa7b0802STobias Grosser }
704fa7b0802STobias Grosser 
705fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
706abed4969SSiddharth Bhat   if (!ManagedMemory)
7077287aeddSTobias Grosser     freeDeviceArrays();
708abed4969SSiddharth Bhat 
709fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
710fa7b0802STobias Grosser   IslNodeBuilder::finalize();
711fa7b0802STobias Grosser }
712fa7b0802STobias Grosser 
713fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
714abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory will directly send host pointers "
715abed4969SSiddharth Bhat                            "to the kernel. There is no need for device arrays");
716fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
717fa7b0802STobias Grosser 
718fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
719fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
72013c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
7217287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
7227287aeddSTobias Grosser     DevArrayName.append(Array->name);
723fa7b0802STobias Grosser 
72413c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
725aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(Array);
726aaabbbf8STobias Grosser     if (Offset)
727aaabbbf8STobias Grosser       ArraySize = Builder.CreateSub(
728aaabbbf8STobias Grosser           ArraySize,
729aaabbbf8STobias Grosser           Builder.CreateMul(Offset,
730aaabbbf8STobias Grosser                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
7317287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
7327287aeddSTobias Grosser     DevArray->setName(DevArrayName);
73313c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
734fa7b0802STobias Grosser   }
735fa7b0802STobias Grosser 
736fa7b0802STobias Grosser   isl_ast_build_free(Build);
737fa7b0802STobias Grosser }
738fa7b0802STobias Grosser 
739c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
740c1c6a2a6STobias Grosser                                         Value *BlockDimY, Value *BlockDimZ) {
741c1c6a2a6STobias Grosser   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
742c1c6a2a6STobias Grosser 
743c1c6a2a6STobias Grosser   for (auto &F : *M) {
744c1c6a2a6STobias Grosser     if (F.getCallingConv() != CallingConv::PTX_Kernel)
745c1c6a2a6STobias Grosser       continue;
746c1c6a2a6STobias Grosser 
747c1c6a2a6STobias Grosser     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
748c1c6a2a6STobias Grosser 
749c1c6a2a6STobias Grosser     Metadata *Elements[] = {
750c1c6a2a6STobias Grosser         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
751c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
752c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
753c1c6a2a6STobias Grosser         ValueAsMetadata::get(V[2]),
754c1c6a2a6STobias Grosser     };
755c1c6a2a6STobias Grosser     MDNode *Node = MDNode::get(M->getContext(), Elements);
756c1c6a2a6STobias Grosser     AnnotationNode->addOperand(Node);
757c1c6a2a6STobias Grosser   }
758c1c6a2a6STobias Grosser }
759c1c6a2a6STobias Grosser 
7607287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
761abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not use device arrays");
76213c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
76313c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
7647287aeddSTobias Grosser }
7657287aeddSTobias Grosser 
76657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
76757793596STobias Grosser   const char *Name = "polly_getKernel";
76857793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
76957793596STobias Grosser   Function *F = M->getFunction(Name);
77057793596STobias Grosser 
77157793596STobias Grosser   // If F is not available, declare it.
77257793596STobias Grosser   if (!F) {
77357793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
77457793596STobias Grosser     std::vector<Type *> Args;
77557793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
77657793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
77757793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
77857793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
77957793596STobias Grosser   }
78057793596STobias Grosser 
78157793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
78257793596STobias Grosser }
78357793596STobias Grosser 
78479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
78579a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
78679a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
78779a947c2STobias Grosser   Function *F = M->getFunction(Name);
78879a947c2STobias Grosser 
78979a947c2STobias Grosser   // If F is not available, declare it.
79079a947c2STobias Grosser   if (!F) {
79179a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
79279a947c2STobias Grosser     std::vector<Type *> Args;
79379a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
79479a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
79579a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
79679a947c2STobias Grosser   }
79779a947c2STobias Grosser 
79879a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
79979a947c2STobias Grosser }
80079a947c2STobias Grosser 
80179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
80279a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
80379a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
80479a947c2STobias Grosser                                             Value *Parameters) {
80579a947c2STobias Grosser   const char *Name = "polly_launchKernel";
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     Args.push_back(Builder.getInt32Ty());
81579a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
81679a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
81779a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
81879a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
81979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
82079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
82179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
82279a947c2STobias Grosser   }
82379a947c2STobias Grosser 
824ff40087aSTobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
82579a947c2STobias Grosser                          BlockDimZ, Parameters});
82679a947c2STobias Grosser }
82779a947c2STobias Grosser 
82857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
82957793596STobias Grosser   const char *Name = "polly_freeKernel";
83057793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
83157793596STobias Grosser   Function *F = M->getFunction(Name);
83257793596STobias Grosser 
83357793596STobias Grosser   // If F is not available, declare it.
83457793596STobias Grosser   if (!F) {
83557793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
83657793596STobias Grosser     std::vector<Type *> Args;
83757793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
83857793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
83957793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
84057793596STobias Grosser   }
84157793596STobias Grosser 
84257793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
84357793596STobias Grosser }
84457793596STobias Grosser 
8457287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
846abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
847abed4969SSiddharth Bhat                            "for device");
8487287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
8497287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8507287aeddSTobias Grosser   Function *F = M->getFunction(Name);
8517287aeddSTobias Grosser 
8527287aeddSTobias Grosser   // If F is not available, declare it.
8537287aeddSTobias Grosser   if (!F) {
8547287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
8557287aeddSTobias Grosser     std::vector<Type *> Args;
8567287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
8577287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
8587287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
8597287aeddSTobias Grosser   }
8607287aeddSTobias Grosser 
8617287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
8627287aeddSTobias Grosser }
8637287aeddSTobias Grosser 
864fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
865abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not allocate or free memory "
866abed4969SSiddharth Bhat                            "for device");
867fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
868fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
869fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
870fa7b0802STobias Grosser 
871fa7b0802STobias Grosser   // If F is not available, declare it.
872fa7b0802STobias Grosser   if (!F) {
873fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
874fa7b0802STobias Grosser     std::vector<Type *> Args;
875fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
876fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
877fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
878fa7b0802STobias Grosser   }
879fa7b0802STobias Grosser 
880fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
881fa7b0802STobias Grosser }
882fa7b0802STobias Grosser 
88313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
88413c78e4dSTobias Grosser                                                     Value *DeviceData,
88513c78e4dSTobias Grosser                                                     Value *Size) {
886abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
887abed4969SSiddharth Bhat                            "device and host");
88813c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
88913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
89013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
89113c78e4dSTobias Grosser 
89213c78e4dSTobias Grosser   // If F is not available, declare it.
89313c78e4dSTobias Grosser   if (!F) {
89413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
89513c78e4dSTobias Grosser     std::vector<Type *> Args;
89613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
89813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
89913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
90013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
90113c78e4dSTobias Grosser   }
90213c78e4dSTobias Grosser 
90313c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
90413c78e4dSTobias Grosser }
90513c78e4dSTobias Grosser 
90613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
90713c78e4dSTobias Grosser                                                     Value *HostData,
90813c78e4dSTobias Grosser                                                     Value *Size) {
909abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory does not transfer memory between "
910abed4969SSiddharth Bhat                            "device and host");
91113c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
91213c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
91313c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
91413c78e4dSTobias Grosser 
91513c78e4dSTobias Grosser   // If F is not available, declare it.
91613c78e4dSTobias Grosser   if (!F) {
91713c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
91813c78e4dSTobias Grosser     std::vector<Type *> Args;
91913c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
92013c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
92113c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
92213c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
92313c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
92413c78e4dSTobias Grosser   }
92513c78e4dSTobias Grosser 
92613c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
92713c78e4dSTobias Grosser }
92813c78e4dSTobias Grosser 
929abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() {
930abed4969SSiddharth Bhat   assert(ManagedMemory && "explicit synchronization is only necessary for "
931abed4969SSiddharth Bhat                           "managed memory");
932abed4969SSiddharth Bhat   const char *Name = "polly_synchronizeDevice";
933abed4969SSiddharth Bhat   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
934abed4969SSiddharth Bhat   Function *F = M->getFunction(Name);
935abed4969SSiddharth Bhat 
936abed4969SSiddharth Bhat   // If F is not available, declare it.
937abed4969SSiddharth Bhat   if (!F) {
938abed4969SSiddharth Bhat     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
939abed4969SSiddharth Bhat     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
940abed4969SSiddharth Bhat     F = Function::Create(Ty, Linkage, Name, M);
941abed4969SSiddharth Bhat   }
942abed4969SSiddharth Bhat 
943abed4969SSiddharth Bhat   Builder.CreateCall(F);
944abed4969SSiddharth Bhat }
945abed4969SSiddharth Bhat 
946fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
94717f01968SSiddharth Bhat   const char *Name;
94817f01968SSiddharth Bhat 
94917f01968SSiddharth Bhat   switch (Runtime) {
95017f01968SSiddharth Bhat   case GPURuntime::CUDA:
95117f01968SSiddharth Bhat     Name = "polly_initContextCUDA";
95217f01968SSiddharth Bhat     break;
95317f01968SSiddharth Bhat   case GPURuntime::OpenCL:
95417f01968SSiddharth Bhat     Name = "polly_initContextCL";
95517f01968SSiddharth Bhat     break;
95617f01968SSiddharth Bhat   }
95717f01968SSiddharth Bhat 
958fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
959fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
960fa7b0802STobias Grosser 
961fa7b0802STobias Grosser   // If F is not available, declare it.
962fa7b0802STobias Grosser   if (!F) {
963fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
964fa7b0802STobias Grosser     std::vector<Type *> Args;
965fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
966fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
967fa7b0802STobias Grosser   }
968fa7b0802STobias Grosser 
969fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
970fa7b0802STobias Grosser }
971fa7b0802STobias Grosser 
972fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
973fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
974fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
975fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
976fa7b0802STobias Grosser 
977fa7b0802STobias Grosser   // If F is not available, declare it.
978fa7b0802STobias Grosser   if (!F) {
979fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
980fa7b0802STobias Grosser     std::vector<Type *> Args;
981fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
982fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
983fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
984fa7b0802STobias Grosser   }
985fa7b0802STobias Grosser 
986fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
987fa7b0802STobias Grosser }
988fa7b0802STobias Grosser 
9895260c041STobias Grosser /// Check if one string is a prefix of another.
9905260c041STobias Grosser ///
9915260c041STobias Grosser /// @param String The string in which to look for the prefix.
9925260c041STobias Grosser /// @param Prefix The prefix to look for.
9935260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
9945260c041STobias Grosser   return String.find(Prefix) == 0;
9955260c041STobias Grosser }
9965260c041STobias Grosser 
99713c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
99813c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
99913c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
100013c78e4dSTobias Grosser 
100113c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
100213c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
100313c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
100413c78e4dSTobias Grosser 
100513c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
100613c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
100713c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
100813c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
100913c78e4dSTobias Grosser     }
101013c78e4dSTobias Grosser 
101113c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
1012b79f4d39STobias Grosser     if (NumElements->getType() != ArraySize->getType())
1013b79f4d39STobias Grosser       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
101413c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
101513c78e4dSTobias Grosser   }
101613c78e4dSTobias Grosser   isl_ast_build_free(Build);
101713c78e4dSTobias Grosser   return ArraySize;
101813c78e4dSTobias Grosser }
101913c78e4dSTobias Grosser 
1020aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1021aaabbbf8STobias Grosser   if (gpu_array_is_scalar(Array))
1022aaabbbf8STobias Grosser     return nullptr;
1023aaabbbf8STobias Grosser 
1024aaabbbf8STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
1025aaabbbf8STobias Grosser 
1026aaabbbf8STobias Grosser   isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent));
1027aaabbbf8STobias Grosser 
1028aaabbbf8STobias Grosser   isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min));
1029aaabbbf8STobias Grosser 
1030aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++)
1031aaabbbf8STobias Grosser     ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0);
1032aaabbbf8STobias Grosser 
1033aaabbbf8STobias Grosser   if (isl_set_is_subset(Min, ZeroSet)) {
1034aaabbbf8STobias Grosser     isl_set_free(Min);
1035aaabbbf8STobias Grosser     isl_set_free(ZeroSet);
1036aaabbbf8STobias Grosser     isl_ast_build_free(Build);
1037aaabbbf8STobias Grosser     return nullptr;
1038aaabbbf8STobias Grosser   }
1039aaabbbf8STobias Grosser   isl_set_free(ZeroSet);
1040aaabbbf8STobias Grosser 
1041aaabbbf8STobias Grosser   isl_ast_expr *Result =
1042aaabbbf8STobias Grosser       isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0));
1043aaabbbf8STobias Grosser 
1044aaabbbf8STobias Grosser   for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) {
1045aaabbbf8STobias Grosser     if (i > 0) {
1046aaabbbf8STobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]);
1047aaabbbf8STobias Grosser       isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
1048aaabbbf8STobias Grosser       Result = isl_ast_expr_mul(Result, BExpr);
1049aaabbbf8STobias Grosser     }
1050aaabbbf8STobias Grosser     isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i);
1051aaabbbf8STobias Grosser     isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin);
1052aaabbbf8STobias Grosser     Result = isl_ast_expr_add(Result, MExpr);
1053aaabbbf8STobias Grosser   }
1054aaabbbf8STobias Grosser 
1055aaabbbf8STobias Grosser   Value *ResultValue = ExprBuilder.create(Result);
1056aaabbbf8STobias Grosser   isl_set_free(Min);
1057aaabbbf8STobias Grosser   isl_ast_build_free(Build);
1058aaabbbf8STobias Grosser 
1059aaabbbf8STobias Grosser   return ResultValue;
1060aaabbbf8STobias Grosser }
1061aaabbbf8STobias Grosser 
1062abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array,
1063abed4969SSiddharth Bhat                                                      ScopArrayInfo *ArrayInfo) {
1064abed4969SSiddharth Bhat 
1065abed4969SSiddharth Bhat   assert(ManagedMemory && "Only used when you wish to get a host "
1066abed4969SSiddharth Bhat                           "pointer for sending data to the kernel, "
1067abed4969SSiddharth Bhat                           "with managed memory");
1068abed4969SSiddharth Bhat   std::map<ScopArrayInfo *, Value *>::iterator it;
1069abed4969SSiddharth Bhat   if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) {
1070abed4969SSiddharth Bhat     return it->second;
1071abed4969SSiddharth Bhat   } else {
1072abed4969SSiddharth Bhat     Value *HostPtr;
1073abed4969SSiddharth Bhat 
1074abed4969SSiddharth Bhat     if (gpu_array_is_scalar(Array))
1075abed4969SSiddharth Bhat       HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo);
1076abed4969SSiddharth Bhat     else
1077abed4969SSiddharth Bhat       HostPtr = ArrayInfo->getBasePtr();
1078abed4969SSiddharth Bhat 
1079abed4969SSiddharth Bhat     Value *Offset = getArrayOffset(Array);
1080abed4969SSiddharth Bhat     if (Offset) {
1081abed4969SSiddharth Bhat       HostPtr = Builder.CreatePointerCast(
1082abed4969SSiddharth Bhat           HostPtr, ArrayInfo->getElementType()->getPointerTo());
1083abed4969SSiddharth Bhat       HostPtr = Builder.CreateGEP(HostPtr, Offset);
1084abed4969SSiddharth Bhat     }
1085abed4969SSiddharth Bhat 
1086abed4969SSiddharth Bhat     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1087abed4969SSiddharth Bhat     DeviceAllocations[ArrayInfo] = HostPtr;
1088abed4969SSiddharth Bhat     return HostPtr;
1089abed4969SSiddharth Bhat   }
1090abed4969SSiddharth Bhat }
1091abed4969SSiddharth Bhat 
109213c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
109313c78e4dSTobias Grosser                                         enum DataDirection Direction) {
1094abed4969SSiddharth Bhat   assert(!ManagedMemory && "Managed memory needs no data transfers");
109513c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
109613c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
109713c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
109813c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
109913c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
110013c78e4dSTobias Grosser 
110113c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
1102aaabbbf8STobias Grosser   Value *Offset = getArrayOffset(Array);
110313c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
110413c78e4dSTobias Grosser 
1105b06ff457STobias Grosser   Value *HostPtr;
1106b06ff457STobias Grosser 
1107b06ff457STobias Grosser   if (gpu_array_is_scalar(Array))
1108b06ff457STobias Grosser     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1109b06ff457STobias Grosser   else
1110b06ff457STobias Grosser     HostPtr = ScopArray->getBasePtr();
111113c78e4dSTobias Grosser 
1112aaabbbf8STobias Grosser   if (Offset) {
1113aaabbbf8STobias Grosser     HostPtr = Builder.CreatePointerCast(
1114aaabbbf8STobias Grosser         HostPtr, ScopArray->getElementType()->getPointerTo());
1115aaabbbf8STobias Grosser     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1116aaabbbf8STobias Grosser   }
1117aaabbbf8STobias Grosser 
111813c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
111913c78e4dSTobias Grosser 
1120aaabbbf8STobias Grosser   if (Offset) {
1121aaabbbf8STobias Grosser     Size = Builder.CreateSub(
1122ff40087aSTobias Grosser         Size, Builder.CreateMul(
1123ff40087aSTobias Grosser                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1124aaabbbf8STobias Grosser   }
1125aaabbbf8STobias Grosser 
112613c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
112713c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
112813c78e4dSTobias Grosser   else
112913c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
113013c78e4dSTobias Grosser 
113113c78e4dSTobias Grosser   isl_id_free(Id);
113213c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
113313c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
113413c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
113513c78e4dSTobias Grosser }
113613c78e4dSTobias Grosser 
11371fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
113832837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
113932837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
114032837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
114132837fe3STobias Grosser   isl_id_free(Id);
114232837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
114332837fe3STobias Grosser 
114432837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
114532837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
114632837fe3STobias Grosser     createKernel(UserStmt);
114732837fe3STobias Grosser     isl_ast_expr_free(Expr);
114832837fe3STobias Grosser     return;
114932837fe3STobias Grosser   }
115032837fe3STobias Grosser 
115113c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
1152abed4969SSiddharth Bhat     if (!ManagedMemory)
115313c78e4dSTobias Grosser       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1154abed4969SSiddharth Bhat     else
1155abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1156abed4969SSiddharth Bhat 
115732837fe3STobias Grosser     isl_ast_expr_free(Expr);
115813c78e4dSTobias Grosser     return;
115913c78e4dSTobias Grosser   }
116013c78e4dSTobias Grosser 
116113c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
1162abed4969SSiddharth Bhat     if (!ManagedMemory) {
116313c78e4dSTobias Grosser       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1164abed4969SSiddharth Bhat     } else {
1165abed4969SSiddharth Bhat       createCallSynchronizeDevice();
1166abed4969SSiddharth Bhat       isl_ast_node_free(UserStmt);
1167abed4969SSiddharth Bhat     }
116813c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
116938fc0aedSTobias Grosser     return;
117038fc0aedSTobias Grosser   }
117138fc0aedSTobias Grosser 
11725260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
11735260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
11745260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
11755260c041STobias Grosser   isl_id_free(Anno);
11765260c041STobias Grosser 
11775260c041STobias Grosser   switch (KernelStmt->type) {
11785260c041STobias Grosser   case ppcg_kernel_domain:
1179edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
11805260c041STobias Grosser     isl_ast_node_free(UserStmt);
11815260c041STobias Grosser     return;
11825260c041STobias Grosser   case ppcg_kernel_copy:
1183b513b491STobias Grosser     createKernelCopy(KernelStmt);
11845260c041STobias Grosser     isl_ast_expr_free(Expr);
11855260c041STobias Grosser     isl_ast_node_free(UserStmt);
11865260c041STobias Grosser     return;
11875260c041STobias Grosser   case ppcg_kernel_sync:
11885260c041STobias Grosser     createKernelSync();
11895260c041STobias Grosser     isl_ast_expr_free(Expr);
11905260c041STobias Grosser     isl_ast_node_free(UserStmt);
11915260c041STobias Grosser     return;
11925260c041STobias Grosser   }
11935260c041STobias Grosser 
11945260c041STobias Grosser   isl_ast_expr_free(Expr);
11955260c041STobias Grosser   isl_ast_node_free(UserStmt);
11965260c041STobias Grosser   return;
11975260c041STobias Grosser }
1198b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1199b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1200b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1201b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1202b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1203b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
1204b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
1205b513b491STobias Grosser 
1206b513b491STobias Grosser   if (KernelStmt->u.c.read) {
1207b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1208b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
1209b513b491STobias Grosser   } else {
1210b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1211b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
1212b513b491STobias Grosser   }
1213b513b491STobias Grosser }
12145260c041STobias Grosser 
1215edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1216edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
1217edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1218edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1219edb885cbSTobias Grosser 
1220edb885cbSTobias Grosser   LoopToScevMapT LTS;
1221edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1222edb885cbSTobias Grosser 
1223edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
1224edb885cbSTobias Grosser 
1225edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
1226edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1227edb885cbSTobias Grosser   else
1228a82c4b5dSTobias Grosser     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1229edb885cbSTobias Grosser }
1230edb885cbSTobias Grosser 
12315260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
12325260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
123317f01968SSiddharth Bhat 
123417f01968SSiddharth Bhat   Function *Sync;
123517f01968SSiddharth Bhat 
123617f01968SSiddharth Bhat   switch (Arch) {
123717f01968SSiddharth Bhat   case GPUArch::NVPTX64:
123817f01968SSiddharth Bhat     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
123917f01968SSiddharth Bhat     break;
124017f01968SSiddharth Bhat   }
124117f01968SSiddharth Bhat 
12425260c041STobias Grosser   Builder.CreateCall(Sync, {});
12435260c041STobias Grosser }
12445260c041STobias Grosser 
1245edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
1246edb885cbSTobias Grosser ///
1247edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
1248edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
1249edb885cbSTobias Grosser ///
1250edb885cbSTobias Grosser /// @param Node The node to collect references for.
1251edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
1252edb885cbSTobias Grosser ///
1253edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
1254edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1255edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1256edb885cbSTobias Grosser     return isl_bool_true;
1257edb885cbSTobias Grosser 
1258edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1259edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1260edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1261edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
1262edb885cbSTobias Grosser   isl_id_free(Id);
1263edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
1264edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
1265edb885cbSTobias Grosser 
1266edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
1267edb885cbSTobias Grosser     return isl_bool_true;
1268edb885cbSTobias Grosser 
1269edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
1270edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1271edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1272edb885cbSTobias Grosser   isl_id_free(Id);
1273edb885cbSTobias Grosser 
127400bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1275edb885cbSTobias Grosser 
1276edb885cbSTobias Grosser   return isl_bool_true;
1277edb885cbSTobias Grosser }
1278edb885cbSTobias Grosser 
1279f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel.
1280f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) {
1281f291c8d5SSiddharth Bhat   assert(F && "F is an invalid pointer");
1282f291c8d5SSiddharth Bhat   // We string compare against the name of the function to allow
1283f291c8d5SSiddharth Bhat   // all variants of the intrinsic "llvm.sqrt.*"
1284f291c8d5SSiddharth Bhat   return F->isIntrinsic() && F->getName().startswith("llvm.sqrt");
1285f291c8d5SSiddharth Bhat }
1286f291c8d5SSiddharth Bhat 
1287f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value.
1288f291c8d5SSiddharth Bhat ///
1289f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along
1290f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and
1291f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not
1292f291c8d5SSiddharth Bhat /// `Function`s.
1293f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1294f291c8d5SSiddharth Bhat 
1295f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`.
1296f291c8d5SSiddharth Bhat static SetVector<Function *>
1297f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1298f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1299f291c8d5SSiddharth Bhat   for (Value *It : RawSubtreeValues) {
1300f291c8d5SSiddharth Bhat     Function *F = dyn_cast<Function>(It);
1301f291c8d5SSiddharth Bhat     if (F) {
1302f291c8d5SSiddharth Bhat       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1303f291c8d5SSiddharth Bhat                                            "this point if an invalid function "
1304f291c8d5SSiddharth Bhat                                            "were present in a kernel.");
1305f291c8d5SSiddharth Bhat       SubtreeFunctions.insert(F);
1306f291c8d5SSiddharth Bhat     }
1307f291c8d5SSiddharth Bhat   }
1308f291c8d5SSiddharth Bhat   return SubtreeFunctions;
1309f291c8d5SSiddharth Bhat }
1310f291c8d5SSiddharth Bhat 
1311f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>>
1312f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1313edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
1314edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
1315edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1316edb885cbSTobias Grosser   SubtreeReferences References = {
1317edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1318edb885cbSTobias Grosser 
1319edb885cbSTobias Grosser   for (const auto &I : IDToValue)
1320edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
1321edb885cbSTobias Grosser 
1322edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
1323edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
1324edb885cbSTobias Grosser 
1325edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
1326edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
1327edb885cbSTobias Grosser 
1328edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
1329d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
1330edb885cbSTobias Grosser 
1331edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
1332edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1333edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1334edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1335edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1336edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1337edb885cbSTobias Grosser     isl_id_free(Id);
1338edb885cbSTobias Grosser   }
1339edb885cbSTobias Grosser   isl_space_free(Space);
1340edb885cbSTobias Grosser 
1341edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1342edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1343edb885cbSTobias Grosser     assert(IDToValue.count(Id));
1344edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
1345edb885cbSTobias Grosser     SubtreeValues.remove(Val);
1346edb885cbSTobias Grosser     isl_id_free(Id);
1347edb885cbSTobias Grosser   }
1348edb885cbSTobias Grosser 
1349f291c8d5SSiddharth Bhat   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1350f291c8d5SSiddharth Bhat   // SubtreeValues. This is important, because we should not lose any
1351f291c8d5SSiddharth Bhat   // SubtreeValues in the process of constructing the
1352f291c8d5SSiddharth Bhat   // "ValidSubtree{Values, Functions} sets. Nor should the set
1353f291c8d5SSiddharth Bhat   // ValidSubtree{Values, Functions} have any common element.
1354f291c8d5SSiddharth Bhat   auto ValidSubtreeValuesIt =
1355f291c8d5SSiddharth Bhat       make_filter_range(SubtreeValues, isValidSubtreeValue);
1356f291c8d5SSiddharth Bhat   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1357f291c8d5SSiddharth Bhat                                         ValidSubtreeValuesIt.end());
1358f291c8d5SSiddharth Bhat   SetVector<Function *> ValidSubtreeFunctions(
1359f291c8d5SSiddharth Bhat       getFunctionsFromRawSubtreeValues(SubtreeValues));
1360f291c8d5SSiddharth Bhat 
1361f291c8d5SSiddharth Bhat   return std::make_pair(ValidSubtreeValues, ValidSubtreeFunctions);
1362edb885cbSTobias Grosser }
1363edb885cbSTobias Grosser 
136474dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
136574dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
136674dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
136774dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
136874dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
136974dc3cb4STobias Grosser 
137074dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
137174dc3cb4STobias Grosser     DT.eraseNode(BB);
137274dc3cb4STobias Grosser }
137374dc3cb4STobias Grosser 
137474dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
137574dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
137674dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
137774dc3cb4STobias Grosser     if (L)
137874dc3cb4STobias Grosser       SE.forgetLoop(L);
137974dc3cb4STobias Grosser   }
138074dc3cb4STobias Grosser }
138174dc3cb4STobias Grosser 
138274dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
138374dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
138474dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
138574dc3cb4STobias Grosser     if (L)
138674dc3cb4STobias Grosser       SE.forgetLoop(L);
138774dc3cb4STobias Grosser     LI.removeBlock(&BB);
138874dc3cb4STobias Grosser   }
138974dc3cb4STobias Grosser }
139074dc3cb4STobias Grosser 
139179a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
139279a947c2STobias Grosser   std::vector<Value *> Sizes;
139379a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
139479a947c2STobias Grosser 
139579a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
139679a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
139779a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
139879a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
139979a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
140079a947c2STobias Grosser     Sizes.push_back(Res);
140179a947c2STobias Grosser   }
140279a947c2STobias Grosser   isl_ast_build_free(Context);
140379a947c2STobias Grosser 
140479a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
140579a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
140679a947c2STobias Grosser 
140779a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
140879a947c2STobias Grosser }
140979a947c2STobias Grosser 
141079a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
141179a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
141279a947c2STobias Grosser   std::vector<Value *> Sizes;
141379a947c2STobias Grosser 
141479a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
141579a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
141679a947c2STobias Grosser     Sizes.push_back(Res);
141779a947c2STobias Grosser   }
141879a947c2STobias Grosser 
141979a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
142079a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
142179a947c2STobias Grosser 
142279a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
142379a947c2STobias Grosser }
142479a947c2STobias Grosser 
1425a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1426a90be207SSiddharth Bhat                                           Instruction *Param, int Index) {
1427a90be207SSiddharth Bhat   Value *Slot = Builder.CreateGEP(
1428a90be207SSiddharth Bhat       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1429a90be207SSiddharth Bhat   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1430a90be207SSiddharth Bhat   Builder.CreateStore(ParamTyped, Slot);
1431a90be207SSiddharth Bhat }
1432a90be207SSiddharth Bhat 
143357693272STobias Grosser Value *
143457693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
143557693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
1436a90be207SSiddharth Bhat   const int NumArgs = F->arg_size();
1437a90be207SSiddharth Bhat   std::vector<int> ArgSizes(NumArgs);
1438a90be207SSiddharth Bhat 
1439a90be207SSiddharth Bhat   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
144079a947c2STobias Grosser 
144179a947c2STobias Grosser   BasicBlock *EntryBlock =
144279a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
144367726b32STobias Grosser   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
144479a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
144567726b32STobias Grosser   Instruction *Parameters = new AllocaInst(
144667726b32STobias Grosser       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
144779a947c2STobias Grosser 
144879a947c2STobias Grosser   int Index = 0;
144979a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
145079a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
145179a947c2STobias Grosser       continue;
145279a947c2STobias Grosser 
145379a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
145479a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
145579a947c2STobias Grosser 
1456a90be207SSiddharth Bhat     ArgSizes[Index] = SAI->getElemSizeInBytes();
1457a90be207SSiddharth Bhat 
1458abed4969SSiddharth Bhat     Value *DevArray = nullptr;
1459abed4969SSiddharth Bhat     if (ManagedMemory) {
1460abed4969SSiddharth Bhat       DevArray = getOrCreateManagedDeviceArray(
1461abed4969SSiddharth Bhat           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1462abed4969SSiddharth Bhat     } else {
1463abed4969SSiddharth Bhat       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
146479a947c2STobias Grosser       DevArray = createCallGetDevicePtr(DevArray);
1465abed4969SSiddharth Bhat     }
1466abed4969SSiddharth Bhat     assert(DevArray != nullptr && "Array to be offloaded to device not "
1467abed4969SSiddharth Bhat                                   "initialized");
1468aaabbbf8STobias Grosser     Value *Offset = getArrayOffset(&Prog->array[i]);
1469aaabbbf8STobias Grosser 
1470aaabbbf8STobias Grosser     if (Offset) {
1471aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(
1472aaabbbf8STobias Grosser           DevArray, SAI->getElementType()->getPointerTo());
1473aaabbbf8STobias Grosser       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1474aaabbbf8STobias Grosser       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1475aaabbbf8STobias Grosser     }
1476fe74a7a1STobias Grosser     Value *Slot = Builder.CreateGEP(
1477fe74a7a1STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1478aaabbbf8STobias Grosser 
1479fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1480abed4969SSiddharth Bhat       Value *ValPtr = nullptr;
1481abed4969SSiddharth Bhat       if (ManagedMemory)
1482abed4969SSiddharth Bhat         ValPtr = DevArray;
1483abed4969SSiddharth Bhat       else
1484abed4969SSiddharth Bhat         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1485abed4969SSiddharth Bhat 
1486abed4969SSiddharth Bhat       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1487abed4969SSiddharth Bhat                                   " to be stored into Parameters");
1488fe74a7a1STobias Grosser       Value *ValPtrCast =
1489fe74a7a1STobias Grosser           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1490fe74a7a1STobias Grosser       Builder.CreateStore(ValPtrCast, Slot);
1491fe74a7a1STobias Grosser     } else {
149267726b32STobias Grosser       Instruction *Param =
149367726b32STobias Grosser           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
149467726b32STobias Grosser                          Launch + "_param_" + std::to_string(Index),
149579a947c2STobias Grosser                          EntryBlock->getTerminator());
149679a947c2STobias Grosser       Builder.CreateStore(DevArray, Param);
149779a947c2STobias Grosser       Value *ParamTyped =
149879a947c2STobias Grosser           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
149979a947c2STobias Grosser       Builder.CreateStore(ParamTyped, Slot);
1500fe74a7a1STobias Grosser     }
150179a947c2STobias Grosser     Index++;
150279a947c2STobias Grosser   }
150379a947c2STobias Grosser 
1504a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1505a490147cSTobias Grosser 
1506a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1507a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1508a490147cSTobias Grosser     Value *Val = IDToValue[Id];
1509a490147cSTobias Grosser     isl_id_free(Id);
1510a90be207SSiddharth Bhat 
1511a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1512a90be207SSiddharth Bhat 
151367726b32STobias Grosser     Instruction *Param =
151467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
151567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1516a490147cSTobias Grosser                        EntryBlock->getTerminator());
1517a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
1518a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1519a490147cSTobias Grosser     Index++;
1520a490147cSTobias Grosser   }
1521a490147cSTobias Grosser 
1522d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1523d8b94bcaSTobias Grosser 
1524d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
1525d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1526d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
1527d8b94bcaSTobias Grosser     isl_id_free(Id);
1528a90be207SSiddharth Bhat 
1529a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1530a90be207SSiddharth Bhat 
153167726b32STobias Grosser     Instruction *Param =
153267726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
153367726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
1534d8b94bcaSTobias Grosser                        EntryBlock->getTerminator());
1535d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
1536a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1537d8b94bcaSTobias Grosser     Index++;
1538d8b94bcaSTobias Grosser   }
1539d8b94bcaSTobias Grosser 
154057693272STobias Grosser   for (auto Val : SubtreeValues) {
1541a90be207SSiddharth Bhat     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1542a90be207SSiddharth Bhat 
154367726b32STobias Grosser     Instruction *Param =
154467726b32STobias Grosser         new AllocaInst(Val->getType(), AddressSpace,
154567726b32STobias Grosser                        Launch + "_param_" + std::to_string(Index),
154657693272STobias Grosser                        EntryBlock->getTerminator());
154757693272STobias Grosser     Builder.CreateStore(Val, Param);
1548a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
1549a90be207SSiddharth Bhat     Index++;
1550a90be207SSiddharth Bhat   }
1551a90be207SSiddharth Bhat 
1552a90be207SSiddharth Bhat   for (int i = 0; i < NumArgs; i++) {
1553a90be207SSiddharth Bhat     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1554a90be207SSiddharth Bhat     Instruction *Param =
1555a90be207SSiddharth Bhat         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1556a90be207SSiddharth Bhat                        Launch + "_param_size_" + std::to_string(i),
1557a90be207SSiddharth Bhat                        EntryBlock->getTerminator());
1558a90be207SSiddharth Bhat     Builder.CreateStore(Val, Param);
1559a90be207SSiddharth Bhat     insertStoreParameter(Parameters, Param, Index);
156057693272STobias Grosser     Index++;
156157693272STobias Grosser   }
156257693272STobias Grosser 
156379a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
156479a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
156579a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
156679a947c2STobias Grosser }
156779a947c2STobias Grosser 
1568f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions(
1569f291c8d5SSiddharth Bhat     SetVector<Function *> SubtreeFunctions) {
1570f291c8d5SSiddharth Bhat   for (auto Fn : SubtreeFunctions) {
1571f291c8d5SSiddharth Bhat     const std::string ClonedFnName = Fn->getName();
1572f291c8d5SSiddharth Bhat     Function *Clone = GPUModule->getFunction(ClonedFnName);
1573f291c8d5SSiddharth Bhat     if (!Clone)
1574f291c8d5SSiddharth Bhat       Clone =
1575f291c8d5SSiddharth Bhat           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1576f291c8d5SSiddharth Bhat                            ClonedFnName, GPUModule.get());
1577f291c8d5SSiddharth Bhat     assert(Clone && "Expected cloned function to be initialized.");
1578f291c8d5SSiddharth Bhat     assert(ValueMap.find(Fn) == ValueMap.end() &&
1579f291c8d5SSiddharth Bhat            "Fn already present in ValueMap");
1580f291c8d5SSiddharth Bhat     ValueMap[Fn] = Clone;
1581f291c8d5SSiddharth Bhat   }
1582f291c8d5SSiddharth Bhat }
158332837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
158432837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
158532837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
158632837fe3STobias Grosser   isl_id_free(Id);
158732837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
158832837fe3STobias Grosser 
1589bc653f20STobias Grosser   if (Kernel->n_grid > 1)
1590bc653f20STobias Grosser     DeepestParallel =
1591bc653f20STobias Grosser         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1592bc653f20STobias Grosser   else
1593bc653f20STobias Grosser     DeepestSequential =
1594bc653f20STobias Grosser         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1595bc653f20STobias Grosser 
1596c1c6a2a6STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1597c1c6a2a6STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1598c1c6a2a6STobias Grosser 
1599f291c8d5SSiddharth Bhat   SetVector<Value *> SubtreeValues;
1600f291c8d5SSiddharth Bhat   SetVector<Function *> SubtreeFunctions;
1601f291c8d5SSiddharth Bhat   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1602edb885cbSTobias Grosser 
160332837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
160432837fe3STobias Grosser 
160532837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1606472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1607edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
1608587f1f57STobias Grosser   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1609b06ff457STobias Grosser   ScalarMap.clear();
161032837fe3STobias Grosser 
1611edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1612edb885cbSTobias Grosser 
1613edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1614edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1615edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1616edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1617edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1618edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1619edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1620edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1621edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1622edb885cbSTobias Grosser     SubtreeValues.insert(V);
1623edb885cbSTobias Grosser   }
1624edb885cbSTobias Grosser 
1625f291c8d5SSiddharth Bhat   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1626f291c8d5SSiddharth Bhat   setupKernelSubtreeFunctions(SubtreeFunctions);
162732837fe3STobias Grosser 
162859ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
162959ab0705STobias Grosser 
163051dfc275STobias Grosser   finalizeKernelArguments(Kernel);
163174dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
1632c1c6a2a6STobias Grosser   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
163374dc3cb4STobias Grosser   clearDominators(F);
163474dc3cb4STobias Grosser   clearScalarEvolution(F);
163574dc3cb4STobias Grosser   clearLoops(F);
163674dc3cb4STobias Grosser 
1637472f9654STobias Grosser   IDToValue = HostIDs;
163832837fe3STobias Grosser 
1639b06ff457STobias Grosser   ValueMap = std::move(HostValueMap);
1640b06ff457STobias Grosser   ScalarMap = std::move(HostScalarMap);
1641edb885cbSTobias Grosser   EscapeMap.clear();
1642edb885cbSTobias Grosser   IDToSAI.clear();
164374dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
164474dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
16454d5a9172STobias Grosser     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
164674dc3cb4STobias Grosser   LocalArrays.clear();
1647edb885cbSTobias Grosser 
164851dfc275STobias Grosser   std::string ASMString = finalizeKernelFunction();
164951dfc275STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
165057693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
165179a947c2STobias Grosser 
165279f13b9aSSingapuram Sanjay Srivallabh   std::string Name = getKernelFuncName(Kernel->id);
165357793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
165457793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
165557793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
165679a947c2STobias Grosser 
165779a947c2STobias Grosser   Value *GridDimX, *GridDimY;
165879a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
165979a947c2STobias Grosser 
166079a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
166179a947c2STobias Grosser                          BlockDimZ, Parameters);
166257793596STobias Grosser   createCallFreeKernel(GPUKernel);
1663b513b491STobias Grosser 
1664b513b491STobias Grosser   for (auto Id : KernelIds)
1665b513b491STobias Grosser     isl_id_free(Id);
1666b513b491STobias Grosser 
1667b513b491STobias Grosser   KernelIds.clear();
166832837fe3STobias Grosser }
166932837fe3STobias Grosser 
167032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
167132837fe3STobias Grosser ///
167232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
167332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
1674d277fedaSSiddharth Bhat   std::string Ret = "";
167532837fe3STobias Grosser 
1676d277fedaSSiddharth Bhat   if (!is64Bit) {
1677d277fedaSSiddharth Bhat     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1678d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1679d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1680d277fedaSSiddharth Bhat   } else {
1681d277fedaSSiddharth Bhat     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1682d277fedaSSiddharth Bhat            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1683d277fedaSSiddharth Bhat            "64-v128:128:128-n16:32:64";
1684d277fedaSSiddharth Bhat   }
168532837fe3STobias Grosser 
168632837fe3STobias Grosser   return Ret;
168732837fe3STobias Grosser }
168832837fe3STobias Grosser 
1689edb885cbSTobias Grosser Function *
1690edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1691edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
169232837fe3STobias Grosser   std::vector<Type *> Args;
169379f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
169432837fe3STobias Grosser 
169532837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
169632837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
169732837fe3STobias Grosser       continue;
169832837fe3STobias Grosser 
1699fe74a7a1STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1700fe74a7a1STobias Grosser       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1701fe74a7a1STobias Grosser       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1702fe74a7a1STobias Grosser       Args.push_back(SAI->getElementType());
1703fe74a7a1STobias Grosser     } else {
1704d277fedaSSiddharth Bhat       static const int UseGlobalMemory = 1;
1705d277fedaSSiddharth Bhat       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
170632837fe3STobias Grosser     }
1707fe74a7a1STobias Grosser   }
170832837fe3STobias Grosser 
1709f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1710f6044bd0STobias Grosser 
1711f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1712f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1713f6044bd0STobias Grosser 
1714c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1715c84a1995STobias Grosser 
1716cf66ef26STobias Grosser   for (long i = 0; i < NumVars; i++) {
1717cf66ef26STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1718cf66ef26STobias Grosser     Value *Val = IDToValue[Id];
1719cf66ef26STobias Grosser     isl_id_free(Id);
1720cf66ef26STobias Grosser     Args.push_back(Val->getType());
1721cf66ef26STobias Grosser   }
1722c84a1995STobias Grosser 
1723edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1724edb885cbSTobias Grosser     Args.push_back(V->getType());
1725edb885cbSTobias Grosser 
172632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
172732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
172832837fe3STobias Grosser                               GPUModule.get());
172917f01968SSiddharth Bhat 
173017f01968SSiddharth Bhat   switch (Arch) {
173117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
173232837fe3STobias Grosser     FN->setCallingConv(CallingConv::PTX_Kernel);
173317f01968SSiddharth Bhat     break;
173417f01968SSiddharth Bhat   }
173532837fe3STobias Grosser 
173632837fe3STobias Grosser   auto Arg = FN->arg_begin();
173732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
173832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
173932837fe3STobias Grosser       continue;
174032837fe3STobias Grosser 
1741edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1742edb885cbSTobias Grosser 
1743edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1744edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1745edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1746edb885cbSTobias Grosser     Value *Val = &*Arg;
1747edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1748edb885cbSTobias Grosser     isl_ast_build *Build =
1749edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1750f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1751edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1752edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1753edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1754edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1755edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1756edb885cbSTobias Grosser     }
1757edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
17584d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
175974dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1760edb885cbSTobias Grosser 
1761edb885cbSTobias Grosser     isl_ast_build_free(Build);
1762b513b491STobias Grosser     KernelIds.push_back(Id);
1763edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
176432837fe3STobias Grosser     Arg++;
176532837fe3STobias Grosser   }
176632837fe3STobias Grosser 
1767f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1768f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1769f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1770f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1771f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1772f6044bd0STobias Grosser     Arg++;
1773f6044bd0STobias Grosser   }
1774f6044bd0STobias Grosser 
1775c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1776c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1777c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
177812453403STobias Grosser     Value *Val = IDToValue[Id];
177912453403STobias Grosser     ValueMap[Val] = &*Arg;
1780c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1781c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1782c84a1995STobias Grosser     Arg++;
1783c84a1995STobias Grosser   }
1784c84a1995STobias Grosser 
1785edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1786edb885cbSTobias Grosser     Arg->setName(V->getName());
1787edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1788edb885cbSTobias Grosser     Arg++;
1789edb885cbSTobias Grosser   }
1790edb885cbSTobias Grosser 
179132837fe3STobias Grosser   return FN;
179232837fe3STobias Grosser }
179332837fe3STobias Grosser 
1794472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
179517f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsBID[2];
179617f01968SSiddharth Bhat   Intrinsic::ID IntrinsicsTID[3];
1797472f9654STobias Grosser 
179817f01968SSiddharth Bhat   switch (Arch) {
179917f01968SSiddharth Bhat   case GPUArch::NVPTX64:
180017f01968SSiddharth Bhat     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
180117f01968SSiddharth Bhat     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
180217f01968SSiddharth Bhat 
180317f01968SSiddharth Bhat     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
180417f01968SSiddharth Bhat     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
180517f01968SSiddharth Bhat     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
180617f01968SSiddharth Bhat     break;
180717f01968SSiddharth Bhat   }
1808472f9654STobias Grosser 
1809472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1810472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1811472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1812472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1813472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1814472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1815472f9654STobias Grosser     IDToValue[Id] = Val;
1816472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1817472f9654STobias Grosser   };
1818472f9654STobias Grosser 
1819472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1820472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1821472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1822472f9654STobias Grosser   }
1823472f9654STobias Grosser 
1824472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1825472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1826472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1827472f9654STobias Grosser   }
1828472f9654STobias Grosser }
1829472f9654STobias Grosser 
183000bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
183100bb5a99STobias Grosser   auto Arg = FN->arg_begin();
183200bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
183300bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
183400bb5a99STobias Grosser       continue;
183500bb5a99STobias Grosser 
183600bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
183700bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
183800bb5a99STobias Grosser     isl_id_free(Id);
183900bb5a99STobias Grosser 
184000bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
184100bb5a99STobias Grosser       Arg++;
184200bb5a99STobias Grosser       continue;
184300bb5a99STobias Grosser     }
184400bb5a99STobias Grosser 
1845fe74a7a1STobias Grosser     Value *Val = &*Arg;
1846fe74a7a1STobias Grosser 
1847fe74a7a1STobias Grosser     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
184800bb5a99STobias Grosser       Type *TypePtr = SAI->getElementType()->getPointerTo();
1849fe74a7a1STobias Grosser       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1850fe74a7a1STobias Grosser       Val = Builder.CreateLoad(TypedArgPtr);
1851fe74a7a1STobias Grosser     }
1852fe74a7a1STobias Grosser 
1853fe74a7a1STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
185400bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
185500bb5a99STobias Grosser 
185600bb5a99STobias Grosser     Arg++;
185700bb5a99STobias Grosser   }
185800bb5a99STobias Grosser }
185900bb5a99STobias Grosser 
186051dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
186151dfc275STobias Grosser   auto *FN = Builder.GetInsertBlock()->getParent();
186251dfc275STobias Grosser   auto Arg = FN->arg_begin();
186351dfc275STobias Grosser 
186451dfc275STobias Grosser   bool StoredScalar = false;
186551dfc275STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
186651dfc275STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
186751dfc275STobias Grosser       continue;
186851dfc275STobias Grosser 
186951dfc275STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
187051dfc275STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
187151dfc275STobias Grosser     isl_id_free(Id);
187251dfc275STobias Grosser 
187351dfc275STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
187451dfc275STobias Grosser       Arg++;
187551dfc275STobias Grosser       continue;
187651dfc275STobias Grosser     }
187751dfc275STobias Grosser 
187851dfc275STobias Grosser     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
187951dfc275STobias Grosser       Arg++;
188051dfc275STobias Grosser       continue;
188151dfc275STobias Grosser     }
188251dfc275STobias Grosser 
188351dfc275STobias Grosser     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
188451dfc275STobias Grosser     Value *ArgPtr = &*Arg;
188551dfc275STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
188651dfc275STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
188751dfc275STobias Grosser     Value *Val = Builder.CreateLoad(Alloca);
188851dfc275STobias Grosser     Builder.CreateStore(Val, TypedArgPtr);
188951dfc275STobias Grosser     StoredScalar = true;
189051dfc275STobias Grosser 
189151dfc275STobias Grosser     Arg++;
189251dfc275STobias Grosser   }
189351dfc275STobias Grosser 
189451dfc275STobias Grosser   if (StoredScalar)
189551dfc275STobias Grosser     /// In case more than one thread contains scalar stores, the generated
189651dfc275STobias Grosser     /// code might be incorrect, if we only store at the end of the kernel.
189751dfc275STobias Grosser     /// To support this case we need to store these scalars back at each
189851dfc275STobias Grosser     /// memory store or at least before each kernel barrier.
189951dfc275STobias Grosser     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
190051dfc275STobias Grosser       BuildSuccessful = 0;
190151dfc275STobias Grosser }
190251dfc275STobias Grosser 
1903b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1904b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1905b513b491STobias Grosser 
1906b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1907b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1908b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1909b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1910b513b491STobias Grosser 
1911f919d8b3STobias Grosser     Type *ArrayTy = EleTy;
1912b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1913b513b491STobias Grosser 
1914f5aff704SRoman Gareev     Sizes.push_back(nullptr);
1915928d7573STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1916b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1917f919d8b3STobias Grosser       long Bound = isl_val_get_num_si(Val);
1918b513b491STobias Grosser       isl_val_free(Val);
1919b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1920928d7573STobias Grosser     }
1921928d7573STobias Grosser 
1922928d7573STobias Grosser     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1923928d7573STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1924928d7573STobias Grosser       long Bound = isl_val_get_num_si(Val);
1925928d7573STobias Grosser       isl_val_free(Val);
1926b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1927b513b491STobias Grosser     }
1928b513b491STobias Grosser 
1929130ca30fSTobias Grosser     const ScopArrayInfo *SAI;
1930130ca30fSTobias Grosser     Value *Allocation;
1931130ca30fSTobias Grosser     if (Var.type == ppcg_access_shared) {
1932130ca30fSTobias Grosser       auto GlobalVar = new GlobalVariable(
1933130ca30fSTobias Grosser           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1934130ca30fSTobias Grosser           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1935130ca30fSTobias Grosser       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1936f919d8b3STobias Grosser       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1937f919d8b3STobias Grosser 
1938130ca30fSTobias Grosser       Allocation = GlobalVar;
1939130ca30fSTobias Grosser     } else if (Var.type == ppcg_access_private) {
1940130ca30fSTobias Grosser       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1941130ca30fSTobias Grosser     } else {
1942130ca30fSTobias Grosser       llvm_unreachable("unknown variable type");
1943130ca30fSTobias Grosser     }
19444d5a9172STobias Grosser     SAI =
19454d5a9172STobias Grosser         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1946b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1947130ca30fSTobias Grosser     IDToValue[Id] = Allocation;
1948130ca30fSTobias Grosser     LocalArrays.push_back(Allocation);
1949b513b491STobias Grosser     KernelIds.push_back(Id);
1950b513b491STobias Grosser     IDToSAI[Id] = SAI;
1951b513b491STobias Grosser   }
1952b513b491STobias Grosser }
1953b513b491STobias Grosser 
1954f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction(
1955f291c8d5SSiddharth Bhat     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1956f291c8d5SSiddharth Bhat     SetVector<Function *> &SubtreeFunctions) {
195779f13b9aSSingapuram Sanjay Srivallabh   std::string Identifier = getKernelFuncName(Kernel->id);
195832837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
195917f01968SSiddharth Bhat 
196017f01968SSiddharth Bhat   switch (Arch) {
196117f01968SSiddharth Bhat   case GPUArch::NVPTX64:
196217f01968SSiddharth Bhat     if (Runtime == GPURuntime::CUDA)
196332837fe3STobias Grosser       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
196417f01968SSiddharth Bhat     else if (Runtime == GPURuntime::OpenCL)
196517f01968SSiddharth Bhat       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
196632837fe3STobias Grosser     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
196717f01968SSiddharth Bhat     break;
196817f01968SSiddharth Bhat   }
196932837fe3STobias Grosser 
1970edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
197132837fe3STobias Grosser 
197259ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
197332837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
197432837fe3STobias Grosser 
197559ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
197659ab0705STobias Grosser 
197732837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
197832837fe3STobias Grosser   Builder.CreateRetVoid();
197932837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1980472f9654STobias Grosser 
1981629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1982629109b6STobias Grosser 
198300bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1984b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1985472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
198632837fe3STobias Grosser }
198732837fe3STobias Grosser 
198874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
198917f01968SSiddharth Bhat   llvm::Triple GPUTriple;
199017f01968SSiddharth Bhat 
199117f01968SSiddharth Bhat   switch (Arch) {
199217f01968SSiddharth Bhat   case GPUArch::NVPTX64:
199317f01968SSiddharth Bhat     switch (Runtime) {
199417f01968SSiddharth Bhat     case GPURuntime::CUDA:
199517f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
199617f01968SSiddharth Bhat       break;
199717f01968SSiddharth Bhat     case GPURuntime::OpenCL:
199817f01968SSiddharth Bhat       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
199917f01968SSiddharth Bhat       break;
200017f01968SSiddharth Bhat     }
200117f01968SSiddharth Bhat     break;
200217f01968SSiddharth Bhat   }
200317f01968SSiddharth Bhat 
200474dc3cb4STobias Grosser   std::string ErrMsg;
200574dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
200674dc3cb4STobias Grosser 
200774dc3cb4STobias Grosser   if (!GPUTarget) {
200874dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
200974dc3cb4STobias Grosser     return "";
201074dc3cb4STobias Grosser   }
201174dc3cb4STobias Grosser 
201274dc3cb4STobias Grosser   TargetOptions Options;
201374dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
201417f01968SSiddharth Bhat 
201517f01968SSiddharth Bhat   std::string subtarget;
201617f01968SSiddharth Bhat 
201717f01968SSiddharth Bhat   switch (Arch) {
201817f01968SSiddharth Bhat   case GPUArch::NVPTX64:
201917f01968SSiddharth Bhat     subtarget = CudaVersion;
202017f01968SSiddharth Bhat     break;
202117f01968SSiddharth Bhat   }
202217f01968SSiddharth Bhat 
202317f01968SSiddharth Bhat   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
202417f01968SSiddharth Bhat       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
202574dc3cb4STobias Grosser 
202674dc3cb4STobias Grosser   SmallString<0> ASMString;
202774dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
202874dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
202974dc3cb4STobias Grosser 
203074dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
203174dc3cb4STobias Grosser 
203274dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
203374dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
203474dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
203574dc3cb4STobias Grosser     return "";
203674dc3cb4STobias Grosser   }
203774dc3cb4STobias Grosser 
203874dc3cb4STobias Grosser   PM.run(*GPUModule);
203974dc3cb4STobias Grosser 
204074dc3cb4STobias Grosser   return ASMStream.str();
204174dc3cb4STobias Grosser }
204274dc3cb4STobias Grosser 
204357793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
204465d7f72fSSiddharth Bhat 
20455857b701STobias Grosser   if (verifyModule(*GPUModule)) {
204665d7f72fSSiddharth Bhat     DEBUG(dbgs() << "verifyModule failed on module:\n";
204765d7f72fSSiddharth Bhat           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
204865d7f72fSSiddharth Bhat 
204965d7f72fSSiddharth Bhat     if (FailOnVerifyModuleFailure)
205065d7f72fSSiddharth Bhat       llvm_unreachable("VerifyModule failed.");
205165d7f72fSSiddharth Bhat 
20525857b701STobias Grosser     BuildSuccessful = false;
20535857b701STobias Grosser     return "";
20545857b701STobias Grosser   }
205532837fe3STobias Grosser 
205632837fe3STobias Grosser   if (DumpKernelIR)
205732837fe3STobias Grosser     outs() << *GPUModule << "\n";
205832837fe3STobias Grosser 
20599a18d559STobias Grosser   // Optimize module.
20609a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
20619a18d559STobias Grosser   PassManagerBuilder PassBuilder;
20629a18d559STobias Grosser   PassBuilder.OptLevel = 3;
20639a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
20649a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
20659a18d559STobias Grosser   OptPasses.run(*GPUModule);
20669a18d559STobias Grosser 
206774dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
206874dc3cb4STobias Grosser 
206974dc3cb4STobias Grosser   if (DumpKernelASM)
207074dc3cb4STobias Grosser     outs() << Assembly << "\n";
207174dc3cb4STobias Grosser 
207232837fe3STobias Grosser   GPUModule.release();
2073472f9654STobias Grosser   KernelIDs.clear();
207457793596STobias Grosser 
207557793596STobias Grosser   return Assembly;
207632837fe3STobias Grosser }
207732837fe3STobias Grosser 
20789dfe4e7cSTobias Grosser namespace {
20799dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
20809dfe4e7cSTobias Grosser public:
20819dfe4e7cSTobias Grosser   static char ID;
20829dfe4e7cSTobias Grosser 
208317f01968SSiddharth Bhat   GPURuntime Runtime = GPURuntime::CUDA;
208417f01968SSiddharth Bhat 
208517f01968SSiddharth Bhat   GPUArch Architecture = GPUArch::NVPTX64;
208617f01968SSiddharth Bhat 
2087e938517eSTobias Grosser   /// The scop that is currently processed.
2088e938517eSTobias Grosser   Scop *S;
2089e938517eSTobias Grosser 
209038fc0aedSTobias Grosser   LoopInfo *LI;
209138fc0aedSTobias Grosser   DominatorTree *DT;
209238fc0aedSTobias Grosser   ScalarEvolution *SE;
209338fc0aedSTobias Grosser   const DataLayout *DL;
209438fc0aedSTobias Grosser   RegionInfo *RI;
209538fc0aedSTobias Grosser 
20969dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
20979dfe4e7cSTobias Grosser 
2098e938517eSTobias Grosser   /// Construct compilation options for PPCG.
2099e938517eSTobias Grosser   ///
2100e938517eSTobias Grosser   /// @returns The compilation options.
2101e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
2102e938517eSTobias Grosser     auto DebugOptions =
2103e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2104e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2105e938517eSTobias Grosser 
2106e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
2107e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
2108e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
2109e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
21108950ceadSTobias Grosser     DebugOptions->verbose = false;
2111e938517eSTobias Grosser 
2112e938517eSTobias Grosser     Options->debug = DebugOptions;
2113e938517eSTobias Grosser 
2114e938517eSTobias Grosser     Options->reschedule = true;
2115e938517eSTobias Grosser     Options->scale_tile_loops = false;
2116e938517eSTobias Grosser     Options->wrap = false;
2117e938517eSTobias Grosser 
2118e938517eSTobias Grosser     Options->non_negative_parameters = false;
2119e938517eSTobias Grosser     Options->ctx = nullptr;
2120e938517eSTobias Grosser     Options->sizes = nullptr;
2121e938517eSTobias Grosser 
21224eaedde5STobias Grosser     Options->tile_size = 32;
21234eaedde5STobias Grosser 
2124130ca30fSTobias Grosser     Options->use_private_memory = PrivateMemory;
2125b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
2126b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
2127e938517eSTobias Grosser 
2128e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
2129e938517eSTobias Grosser     Options->openmp = false;
2130e938517eSTobias Grosser     Options->linearize_device_arrays = true;
2131e938517eSTobias Grosser     Options->live_range_reordering = false;
2132e938517eSTobias Grosser 
2133e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
2134e938517eSTobias Grosser     Options->opencl_use_gpu = false;
2135e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
2136e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
2137e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
2138e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
2139e938517eSTobias Grosser 
2140e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
2141e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
2142e938517eSTobias Grosser 
2143e938517eSTobias Grosser     return Options;
2144e938517eSTobias Grosser   }
2145e938517eSTobias Grosser 
2146f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2147f384594dSTobias Grosser   ///
2148f384594dSTobias Grosser   /// Instead of a normal access of the form:
2149f384594dSTobias Grosser   ///
2150f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2151f384594dSTobias Grosser   ///
2152f384594dSTobias Grosser   /// a tagged access has the form
2153f384594dSTobias Grosser   ///
2154f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2155f384594dSTobias Grosser   ///
2156f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
2157f384594dSTobias Grosser   /// triggered the access.
2158f384594dSTobias Grosser   ///
2159f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
2160f384594dSTobias Grosser   ///
2161f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
2162f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2163f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2164f384594dSTobias Grosser 
2165f384594dSTobias Grosser     for (auto &Stmt : *S)
2166f384594dSTobias Grosser       for (auto &Acc : Stmt)
2167f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
2168f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
2169f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2170f384594dSTobias Grosser 
2171f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
2172f384594dSTobias Grosser           Space = isl_space_range(Space);
2173f384594dSTobias Grosser           Space = isl_space_from_range(Space);
21746293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2175f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
2176f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
2177f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
2178f384594dSTobias Grosser         }
2179f384594dSTobias Grosser 
2180f384594dSTobias Grosser     return Accesses;
2181f384594dSTobias Grosser   }
2182f384594dSTobias Grosser 
2183f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
2184f384594dSTobias Grosser   ///
2185f384594dSTobias Grosser   /// @see getTaggedAccesses
2186f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
2187f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
2188f384594dSTobias Grosser   }
2189f384594dSTobias Grosser 
2190f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
2191f384594dSTobias Grosser   ///
2192f384594dSTobias Grosser   /// @see getTaggedAccesses
2193f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
2194f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2195f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2196f384594dSTobias Grosser   }
2197f384594dSTobias Grosser 
2198f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
2199f384594dSTobias Grosser   ///
2200f384594dSTobias Grosser   /// @see getTaggedAccesses
2201f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
2202f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2203f384594dSTobias Grosser   }
2204f384594dSTobias Grosser 
2205aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
2206aef5196fSTobias Grosser   ///
2207aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
2208aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
2209aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
2210aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
2211aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
2212aef5196fSTobias Grosser   /// the data format that ppcg expects.
2213aef5196fSTobias Grosser   ///
2214aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2215aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
2216aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
2217bd81a7eeSTobias Grosser         S->getIslCtx(),
2218bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2219aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2220aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
2221aef5196fSTobias Grosser 
2222aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2223aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2224aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2225aef5196fSTobias Grosser     }
2226aef5196fSTobias Grosser 
2227aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
2228d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
2229aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2230aef5196fSTobias Grosser     }
2231aef5196fSTobias Grosser 
2232aef5196fSTobias Grosser     isl_space_free(Space);
2233aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
2234aef5196fSTobias Grosser 
2235aef5196fSTobias Grosser     return Names;
2236aef5196fSTobias Grosser   }
2237aef5196fSTobias Grosser 
2238e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
2239e938517eSTobias Grosser   ///
2240f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
2241f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
2242f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
2243f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
2244e938517eSTobias Grosser   ///
2245e938517eSTobias Grosser   /// @returns A new ppcg scop.
2246e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
2247e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2248e938517eSTobias Grosser 
2249e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
2250a82f2d26SSiddharth Bhat     // enable live range reordering
2251a82f2d26SSiddharth Bhat     PPCGScop->options->live_range_reordering = 1;
2252e938517eSTobias Grosser 
2253e938517eSTobias Grosser     PPCGScop->start = 0;
2254e938517eSTobias Grosser     PPCGScop->end = 0;
2255e938517eSTobias Grosser 
2256f384594dSTobias Grosser     PPCGScop->context = S->getContext();
2257f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
2258e938517eSTobias Grosser     PPCGScop->call = nullptr;
2259f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
2260f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
2261e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
2262f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2263f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
2264f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2265f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
2266e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
2267e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
2268a82f2d26SSiddharth Bhat     PPCGScop->independence =
2269a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2270e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
2271e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
2272e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
2273e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
2274e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
2275e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
2276e938517eSTobias Grosser 
2277f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
2278e938517eSTobias Grosser 
2279a82f2d26SSiddharth Bhat     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
2280a82f2d26SSiddharth Bhat     // If we have something non-trivial to kill, add it to the schedule
2281a82f2d26SSiddharth Bhat     if (KillsInfo.KillsSchedule.get())
2282a82f2d26SSiddharth Bhat       PPCGScop->schedule = isl_schedule_sequence(
2283a82f2d26SSiddharth Bhat           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2284a82f2d26SSiddharth Bhat     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
2285a82f2d26SSiddharth Bhat 
2286a82f2d26SSiddharth Bhat     PPCGScop->names = getNames();
2287e938517eSTobias Grosser     PPCGScop->pet = nullptr;
2288e938517eSTobias Grosser 
2289f384594dSTobias Grosser     compute_tagger(PPCGScop);
2290f384594dSTobias Grosser     compute_dependences(PPCGScop);
2291f384594dSTobias Grosser 
2292e938517eSTobias Grosser     return PPCGScop;
2293e938517eSTobias Grosser   }
2294e938517eSTobias Grosser 
2295a6d48f59SMichael Kruse   /// Collect the array accesses in a statement.
229660f63b49STobias Grosser   ///
229760f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
229860f63b49STobias Grosser   ///
229960f63b49STobias Grosser   /// @returns A list of array accesses.
230060f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
230160f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
230260f63b49STobias Grosser 
230360f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
230460f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
230560f63b49STobias Grosser       Access->read = Acc->isRead();
230660f63b49STobias Grosser       Access->write = Acc->isWrite();
230760f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
230860f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
230960f63b49STobias Grosser       Space = isl_space_range(Space);
231060f63b49STobias Grosser       Space = isl_space_from_range(Space);
23116293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
231260f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
231360f63b49STobias Grosser       Access->tagged_access =
231460f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2315b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
231660f63b49STobias Grosser       Access->ref_id = Acc->getId();
231760f63b49STobias Grosser       Access->next = Accesses;
2318b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
231960f63b49STobias Grosser       Accesses = Access;
232060f63b49STobias Grosser     }
232160f63b49STobias Grosser 
232260f63b49STobias Grosser     return Accesses;
232360f63b49STobias Grosser   }
232460f63b49STobias Grosser 
232569b46751STobias Grosser   /// Collect the list of GPU statements.
232669b46751STobias Grosser   ///
232769b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
232869b46751STobias Grosser   /// as well as a list with all memory accesses.
232969b46751STobias Grosser   ///
233069b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
233169b46751STobias Grosser   ///
233269b46751STobias Grosser   /// @returns A linked-list of statements.
233369b46751STobias Grosser   gpu_stmt *getStatements() {
233469b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
233569b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
233669b46751STobias Grosser 
233769b46751STobias Grosser     int i = 0;
233869b46751STobias Grosser     for (auto &Stmt : *S) {
233969b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
234069b46751STobias Grosser 
234169b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
234269b46751STobias Grosser 
234369b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
234469b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
234560f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
234669b46751STobias Grosser       i++;
234769b46751STobias Grosser     }
234869b46751STobias Grosser 
234969b46751STobias Grosser     return Stmts;
235069b46751STobias Grosser   }
235169b46751STobias Grosser 
235260f63b49STobias Grosser   /// Derive the extent of an array.
235360f63b49STobias Grosser   ///
2354d58acf86STobias Grosser   /// The extent of an array is the set of elements that are within the
2355d58acf86STobias Grosser   /// accessed array. For the inner dimensions, the extent constraints are
2356d58acf86STobias Grosser   /// 0 and the size of the corresponding array dimension. For the first
2357d58acf86STobias Grosser   /// (outermost) dimension, the extent constraints are the minimal and maximal
2358d58acf86STobias Grosser   /// subscript value for the first dimension.
235960f63b49STobias Grosser   ///
236060f63b49STobias Grosser   /// @param Array The array to derive the extent for.
236160f63b49STobias Grosser   ///
236260f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
236360f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2364d58acf86STobias Grosser     unsigned NumDims = Array->getNumberOfDimensions();
236560f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
236660f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2367d58acf86STobias Grosser     Accesses = isl_union_map_detect_equalities(Accesses);
236860f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2369d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2370d58acf86STobias Grosser     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2371d58acf86STobias Grosser     AccessUSet = isl_union_set_coalesce(AccessUSet);
2372d58acf86STobias Grosser 
2373d58acf86STobias Grosser     if (isl_union_set_is_empty(AccessUSet)) {
2374d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2375d58acf86STobias Grosser       return isl_set_empty(Array->getSpace());
2376d58acf86STobias Grosser     }
2377d58acf86STobias Grosser 
2378d58acf86STobias Grosser     if (Array->getNumberOfDimensions() == 0) {
2379d58acf86STobias Grosser       isl_union_set_free(AccessUSet);
2380d58acf86STobias Grosser       return isl_set_universe(Array->getSpace());
2381d58acf86STobias Grosser     }
2382d58acf86STobias Grosser 
238360f63b49STobias Grosser     isl_set *AccessSet =
238460f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
238560f63b49STobias Grosser 
2386d58acf86STobias Grosser     isl_union_set_free(AccessUSet);
2387d58acf86STobias Grosser     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2388d58acf86STobias Grosser 
2389d58acf86STobias Grosser     isl_pw_aff *Val =
2390d58acf86STobias Grosser         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2391d58acf86STobias Grosser 
2392d58acf86STobias Grosser     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2393d58acf86STobias Grosser     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2394d58acf86STobias Grosser     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2395d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2396d58acf86STobias Grosser     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2397d58acf86STobias Grosser                                    isl_pw_aff_dim(Val, isl_dim_in));
2398d58acf86STobias Grosser     OuterMin =
2399d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2400d58acf86STobias Grosser     OuterMax =
2401d58acf86STobias Grosser         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2402d58acf86STobias Grosser 
2403d58acf86STobias Grosser     isl_set *Extent = isl_set_universe(Array->getSpace());
2404d58acf86STobias Grosser 
2405d58acf86STobias Grosser     Extent = isl_set_intersect(
2406d58acf86STobias Grosser         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2407d58acf86STobias Grosser     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2408d58acf86STobias Grosser 
2409d58acf86STobias Grosser     for (unsigned i = 1; i < NumDims; ++i)
2410d58acf86STobias Grosser       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2411d58acf86STobias Grosser 
2412b7f68b8cSSiddharth Bhat     for (unsigned i = 0; i < NumDims; ++i) {
2413d58acf86STobias Grosser       isl_pw_aff *PwAff =
2414d58acf86STobias Grosser           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2415b7f68b8cSSiddharth Bhat 
2416b7f68b8cSSiddharth Bhat       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2417b7f68b8cSSiddharth Bhat       // Fortran array will we have a legitimate dimension.
2418b7f68b8cSSiddharth Bhat       if (!PwAff) {
2419b7f68b8cSSiddharth Bhat         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2420b7f68b8cSSiddharth Bhat         continue;
2421b7f68b8cSSiddharth Bhat       }
2422b7f68b8cSSiddharth Bhat 
2423d58acf86STobias Grosser       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2424d58acf86STobias Grosser           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2425d58acf86STobias Grosser       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2426d58acf86STobias Grosser                                   isl_pw_aff_dim(Val, isl_dim_in));
2427d58acf86STobias Grosser       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2428d58acf86STobias Grosser                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2429d58acf86STobias Grosser       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2430d58acf86STobias Grosser       Extent = isl_set_intersect(Set, Extent);
2431d58acf86STobias Grosser     }
2432d58acf86STobias Grosser 
2433d58acf86STobias Grosser     return Extent;
243460f63b49STobias Grosser   }
243560f63b49STobias Grosser 
243660f63b49STobias Grosser   /// Derive the bounds of an array.
243760f63b49STobias Grosser   ///
243860f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
243960f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
244060f63b49STobias Grosser   /// ScopArrayInfo.
244160f63b49STobias Grosser   ///
244260f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
244360f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
244460f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
244560f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
244602293ed7STobias Grosser       if (isl_set_is_empty(PPCGArray.extent)) {
244702293ed7STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
244802293ed7STobias Grosser         isl_local_space *LS = isl_local_space_from_space(
244902293ed7STobias Grosser             isl_space_params(isl_set_get_space(Dom)));
245002293ed7STobias Grosser         isl_set_free(Dom);
245102293ed7STobias Grosser         isl_aff *Zero = isl_aff_zero_on_domain(LS);
245202293ed7STobias Grosser         PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero);
245302293ed7STobias Grosser       } else {
245460f63b49STobias Grosser         isl_set *Dom = isl_set_copy(PPCGArray.extent);
245560f63b49STobias Grosser         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
245660f63b49STobias Grosser         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
245760f63b49STobias Grosser         isl_set_free(Dom);
245860f63b49STobias Grosser         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
245902293ed7STobias Grosser         isl_local_space *LS =
246002293ed7STobias Grosser             isl_local_space_from_space(isl_set_get_space(Dom));
246160f63b49STobias Grosser         isl_aff *One = isl_aff_zero_on_domain(LS);
246260f63b49STobias Grosser         One = isl_aff_add_constant_si(One, 1);
246360f63b49STobias Grosser         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
246460f63b49STobias Grosser         Bound = isl_pw_aff_gist(Bound, S->getContext());
246560f63b49STobias Grosser         PPCGArray.bound[0] = Bound;
246660f63b49STobias Grosser       }
246702293ed7STobias Grosser     }
246860f63b49STobias Grosser 
246960f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
247060f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
247160f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
247260f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
247360f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
247460f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
247560f63b49STobias Grosser     }
247660f63b49STobias Grosser   }
247760f63b49STobias Grosser 
247860f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
247960f63b49STobias Grosser   ///
248060f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
248160f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
248260f63b49STobias Grosser     int i = 0;
2483d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
248460f63b49STobias Grosser       std::string TypeName;
248560f63b49STobias Grosser       raw_string_ostream OS(TypeName);
248660f63b49STobias Grosser 
248760f63b49STobias Grosser       OS << *Array->getElementType();
248860f63b49STobias Grosser       TypeName = OS.str();
248960f63b49STobias Grosser 
249060f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
249160f63b49STobias Grosser 
249260f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
249360f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
249460f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
249560f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
249660f63b49STobias Grosser       PPCGArray.extent = nullptr;
249760f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
249860f63b49STobias Grosser       PPCGArray.bound =
249960f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
250060f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
250160f63b49STobias Grosser       PPCGArray.n_ref = 0;
250260f63b49STobias Grosser       PPCGArray.refs = nullptr;
250360f63b49STobias Grosser       PPCGArray.accessed = true;
2504fe74a7a1STobias Grosser       PPCGArray.read_only_scalar =
2505fe74a7a1STobias Grosser           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
250660f63b49STobias Grosser       PPCGArray.has_compound_element = false;
250760f63b49STobias Grosser       PPCGArray.local = false;
250860f63b49STobias Grosser       PPCGArray.declare_local = false;
250960f63b49STobias Grosser       PPCGArray.global = false;
251060f63b49STobias Grosser       PPCGArray.linearize = false;
251160f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
251213c78e4dSTobias Grosser       PPCGArray.user = Array;
251360f63b49STobias Grosser 
251460f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
25152d010dafSTobias Grosser       i++;
2516b9fc860aSTobias Grosser 
2517b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
251860f63b49STobias Grosser     }
251960f63b49STobias Grosser   }
252060f63b49STobias Grosser 
252160f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
252260f63b49STobias Grosser   ///
252360f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
252460f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
252560f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
252660f63b49STobias Grosser 
2527d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
252860f63b49STobias Grosser       isl_space *Space = Array->getSpace();
252960f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
253060f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
253160f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
253260f63b49STobias Grosser     }
253360f63b49STobias Grosser 
253460f63b49STobias Grosser     return Maps;
253560f63b49STobias Grosser   }
253660f63b49STobias Grosser 
2537e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
2538e938517eSTobias Grosser   ///
2539a6d48f59SMichael Kruse   /// @returns A new gpu program description.
2540e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2541e938517eSTobias Grosser 
2542e938517eSTobias Grosser     if (!PPCGScop)
2543e938517eSTobias Grosser       return nullptr;
2544e938517eSTobias Grosser 
2545e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2546e938517eSTobias Grosser 
2547e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
2548e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
2549aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
255060f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
255160f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
255260f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
255360f63b49STobias Grosser     PPCGProg->tagged_must_kill =
255460f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
255560f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
255660f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
2557e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
2558a82f2d26SSiddharth Bhat 
2559a82f2d26SSiddharth Bhat     // this needs to be set when live range reordering is enabled.
2560a82f2d26SSiddharth Bhat     // NOTE: I believe that is conservatively correct. I'm not sure
2561a82f2d26SSiddharth Bhat     //       what the semantics of this is.
2562a82f2d26SSiddharth Bhat     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2563a82f2d26SSiddharth Bhat     PPCGProg->array_order =
2564a82f2d26SSiddharth Bhat         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
256569b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
256669b46751STobias Grosser     PPCGProg->stmts = getStatements();
256760f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
256860f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
256960f63b49STobias Grosser                                        PPCGProg->n_array);
257060f63b49STobias Grosser 
257160f63b49STobias Grosser     createArrays(PPCGProg);
2572e938517eSTobias Grosser 
2573d58acf86STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2574e938517eSTobias Grosser     return PPCGProg;
2575e938517eSTobias Grosser   }
2576e938517eSTobias Grosser 
257769b46751STobias Grosser   struct PrintGPUUserData {
257869b46751STobias Grosser     struct cuda_info *CudaInfo;
257969b46751STobias Grosser     struct gpu_prog *PPCGProg;
258069b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
258169b46751STobias Grosser   };
258269b46751STobias Grosser 
258369b46751STobias Grosser   /// Print a user statement node in the host code.
258469b46751STobias Grosser   ///
258569b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
258669b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
258769b46751STobias Grosser   /// host ast.
258869b46751STobias Grosser   ///
258969b46751STobias Grosser   /// @param P The printer to print to
259069b46751STobias Grosser   /// @param Options The printing options to use
259169b46751STobias Grosser   /// @param Node The node to print
259269b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
259369b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
259469b46751STobias Grosser   ///
259569b46751STobias Grosser   /// @returns A printer to which the output has been printed.
259669b46751STobias Grosser   static __isl_give isl_printer *
259769b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
259869b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
259969b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
260069b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
260169b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
260269b46751STobias Grosser 
260369b46751STobias Grosser     if (Id) {
260420251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
260520251734STobias Grosser 
260620251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
260720251734STobias Grosser       // otherwise try to call pet functionality that is not available in
260820251734STobias Grosser       // Polly.
260920251734STobias Grosser       if (IsUser) {
261020251734STobias Grosser         P = isl_printer_start_line(P);
261120251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
261220251734STobias Grosser         P = isl_printer_end_line(P);
261320251734STobias Grosser         isl_id_free(Id);
261420251734STobias Grosser         isl_ast_print_options_free(Options);
261520251734STobias Grosser         return P;
261620251734STobias Grosser       }
261720251734STobias Grosser 
261869b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
261969b46751STobias Grosser       isl_id_free(Id);
262069b46751STobias Grosser       Data->Kernels.push_back(Kernel);
262169b46751STobias Grosser     }
262269b46751STobias Grosser 
262369b46751STobias Grosser     return print_host_user(P, Options, Node, User);
262469b46751STobias Grosser   }
262569b46751STobias Grosser 
262669b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
262769b46751STobias Grosser   ///
262869b46751STobias Grosser   /// @param Kernel The kernel to print
262969b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
263069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
263169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
263269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
263369b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
263469b46751STobias Grosser     char *String = isl_printer_get_str(P);
263569b46751STobias Grosser     printf("%s\n", String);
263669b46751STobias Grosser     free(String);
263769b46751STobias Grosser     isl_printer_free(P);
263869b46751STobias Grosser   }
263969b46751STobias Grosser 
264069b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
264169b46751STobias Grosser   ///
264269b46751STobias Grosser   /// @param Tree An AST describing GPU code
264369b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
264469b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
264569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
264669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
264769b46751STobias Grosser 
264869b46751STobias Grosser     PrintGPUUserData Data;
264969b46751STobias Grosser     Data.PPCGProg = PPCGProg;
265069b46751STobias Grosser 
265169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
265269b46751STobias Grosser     Options =
265369b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
265469b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
265569b46751STobias Grosser     char *String = isl_printer_get_str(P);
265669b46751STobias Grosser     printf("# host\n");
265769b46751STobias Grosser     printf("%s\n", String);
265869b46751STobias Grosser     free(String);
265969b46751STobias Grosser     isl_printer_free(P);
266069b46751STobias Grosser 
266169b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
266269b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
266369b46751STobias Grosser       printKernel(Kernel);
266469b46751STobias Grosser     }
266569b46751STobias Grosser   }
266669b46751STobias Grosser 
2667f384594dSTobias Grosser   // Generate a GPU program using PPCG.
2668f384594dSTobias Grosser   //
2669f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
2670f384594dSTobias Grosser   //
2671f384594dSTobias Grosser   //  1) Compute new schedule for the program.
2672f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
2673f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
2674f384594dSTobias Grosser   //
2675f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2676f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2677f384594dSTobias Grosser   // strategy directly from this pass.
2678f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2679f384594dSTobias Grosser 
2680f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2681f384594dSTobias Grosser 
2682f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
2683f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
2684f384594dSTobias Grosser     PPCGGen->print = nullptr;
2685f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
268660c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2687f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
2688f384594dSTobias Grosser     PPCGGen->tree = nullptr;
2689f384594dSTobias Grosser     PPCGGen->types.n = 0;
2690f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
2691f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
2692f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
2693f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
2694f384594dSTobias Grosser 
2695f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
2696f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2697f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
26982341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2699f384594dSTobias Grosser 
2700f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
2701f384594dSTobias Grosser 
2702aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
2703aef5196fSTobias Grosser 
270469b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
2705aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
270669b46751STobias Grosser     } else {
2707aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
270869b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
270969b46751STobias Grosser     }
2710aef5196fSTobias Grosser 
2711f384594dSTobias Grosser     if (DumpSchedule) {
2712f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2713f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2714f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
2715f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
2716f384594dSTobias Grosser       if (Schedule)
2717f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
2718f384594dSTobias Grosser       else
2719f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
2720f384594dSTobias Grosser 
2721f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
2722f384594dSTobias Grosser       isl_printer_free(P);
2723f384594dSTobias Grosser     }
2724f384594dSTobias Grosser 
272569b46751STobias Grosser     if (DumpCode) {
272669b46751STobias Grosser       printf("Code\n");
272769b46751STobias Grosser       printf("====\n");
272869b46751STobias Grosser       if (PPCGGen->tree)
272969b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
273069b46751STobias Grosser       else
273169b46751STobias Grosser         printf("No code generated\n");
273269b46751STobias Grosser     }
273369b46751STobias Grosser 
2734f384594dSTobias Grosser     isl_schedule_free(Schedule);
2735f384594dSTobias Grosser 
2736f384594dSTobias Grosser     return PPCGGen;
2737f384594dSTobias Grosser   }
2738f384594dSTobias Grosser 
2739f384594dSTobias Grosser   /// Free gpu_gen structure.
2740f384594dSTobias Grosser   ///
2741f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
2742f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
2743f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
2744f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
2745f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
2746f384594dSTobias Grosser     free(PPCGGen);
2747f384594dSTobias Grosser   }
2748f384594dSTobias Grosser 
2749b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
2750b307ed4dSTobias Grosser   ///
2751b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
2752b307ed4dSTobias Grosser   /// ourselves.
2753b307ed4dSTobias Grosser   ///
2754b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
2755b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
2756b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
2757b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
2758b307ed4dSTobias Grosser     free(PPCGScop->options);
2759b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
2760b307ed4dSTobias Grosser   }
2761b307ed4dSTobias Grosser 
276282f2af35STobias Grosser   /// Approximate the number of points in the set.
276382f2af35STobias Grosser   ///
276482f2af35STobias Grosser   /// This function returns an ast expression that overapproximates the number
276582f2af35STobias Grosser   /// of points in an isl set through the rectangular hull surrounding this set.
276682f2af35STobias Grosser   ///
276782f2af35STobias Grosser   /// @param Set   The set to count.
276882f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
276982f2af35STobias Grosser   ///              expression.
277082f2af35STobias Grosser   ///
277182f2af35STobias Grosser   /// @returns An approximation of the number of points in the set.
277282f2af35STobias Grosser   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
277382f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
277482f2af35STobias Grosser 
277582f2af35STobias Grosser     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
277682f2af35STobias Grosser     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
277782f2af35STobias Grosser 
277882f2af35STobias Grosser     isl_space *Space = isl_set_get_space(Set);
277982f2af35STobias Grosser     Space = isl_space_params(Space);
278082f2af35STobias Grosser     auto *Univ = isl_set_universe(Space);
278182f2af35STobias Grosser     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
278282f2af35STobias Grosser 
278382f2af35STobias Grosser     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
278482f2af35STobias Grosser       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
278582f2af35STobias Grosser       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
278682f2af35STobias Grosser       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
278782f2af35STobias Grosser       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
278882f2af35STobias Grosser       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
278982f2af35STobias Grosser       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
279082f2af35STobias Grosser     }
279182f2af35STobias Grosser 
279282f2af35STobias Grosser     isl_set_free(Set);
279382f2af35STobias Grosser     isl_pw_aff_free(OneAff);
279482f2af35STobias Grosser 
279582f2af35STobias Grosser     return Expr;
279682f2af35STobias Grosser   }
279782f2af35STobias Grosser 
279882f2af35STobias Grosser   /// Approximate a number of dynamic instructions executed by a given
279982f2af35STobias Grosser   /// statement.
280082f2af35STobias Grosser   ///
280182f2af35STobias Grosser   /// @param Stmt  The statement for which to compute the number of dynamic
280282f2af35STobias Grosser   ///              instructions.
280382f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
280482f2af35STobias Grosser   ///              expression.
280582f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
280682f2af35STobias Grosser   ///          by @p Stmt.
280782f2af35STobias Grosser   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
280882f2af35STobias Grosser                                              __isl_keep isl_ast_build *Build) {
280982f2af35STobias Grosser     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
281082f2af35STobias Grosser 
281182f2af35STobias Grosser     long InstCount = 0;
281282f2af35STobias Grosser 
281382f2af35STobias Grosser     if (Stmt.isBlockStmt()) {
281482f2af35STobias Grosser       auto *BB = Stmt.getBasicBlock();
281582f2af35STobias Grosser       InstCount = std::distance(BB->begin(), BB->end());
281682f2af35STobias Grosser     } else {
281782f2af35STobias Grosser       auto *R = Stmt.getRegion();
281882f2af35STobias Grosser 
281982f2af35STobias Grosser       for (auto *BB : R->blocks()) {
282082f2af35STobias Grosser         InstCount += std::distance(BB->begin(), BB->end());
282182f2af35STobias Grosser       }
282282f2af35STobias Grosser     }
282382f2af35STobias Grosser 
282482f2af35STobias Grosser     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
282582f2af35STobias Grosser     auto *InstExpr = isl_ast_expr_from_val(InstVal);
282682f2af35STobias Grosser     return isl_ast_expr_mul(InstExpr, Iterations);
282782f2af35STobias Grosser   }
282882f2af35STobias Grosser 
282982f2af35STobias Grosser   /// Approximate dynamic instructions executed in scop.
283082f2af35STobias Grosser   ///
283182f2af35STobias Grosser   /// @param S     The scop for which to approximate dynamic instructions.
283282f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
283382f2af35STobias Grosser   ///              expression.
283482f2af35STobias Grosser   /// @returns An approximation of the number of dynamic instructions executed
283582f2af35STobias Grosser   ///          in @p S.
283682f2af35STobias Grosser   __isl_give isl_ast_expr *
283782f2af35STobias Grosser   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
283882f2af35STobias Grosser     isl_ast_expr *Instructions;
283982f2af35STobias Grosser 
284082f2af35STobias Grosser     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
284182f2af35STobias Grosser     Instructions = isl_ast_expr_from_val(Zero);
284282f2af35STobias Grosser 
284382f2af35STobias Grosser     for (ScopStmt &Stmt : S) {
284482f2af35STobias Grosser       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
284582f2af35STobias Grosser       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
284682f2af35STobias Grosser     }
284782f2af35STobias Grosser     return Instructions;
284882f2af35STobias Grosser   }
284982f2af35STobias Grosser 
285082f2af35STobias Grosser   /// Create a check that ensures sufficient compute in scop.
285182f2af35STobias Grosser   ///
285282f2af35STobias Grosser   /// @param S     The scop for which to ensure sufficient compute.
285382f2af35STobias Grosser   /// @param Build The isl ast build object to use for creating the ast
285482f2af35STobias Grosser   ///              expression.
285582f2af35STobias Grosser   /// @returns An expression that evaluates to TRUE in case of sufficient
285682f2af35STobias Grosser   ///          compute and to FALSE, otherwise.
285782f2af35STobias Grosser   __isl_give isl_ast_expr *
285882f2af35STobias Grosser   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
285982f2af35STobias Grosser     auto Iterations = getNumberOfIterations(S, Build);
286082f2af35STobias Grosser     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
286182f2af35STobias Grosser     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
286282f2af35STobias Grosser     return isl_ast_expr_ge(Iterations, MinComputeExpr);
286382f2af35STobias Grosser   }
286482f2af35STobias Grosser 
2865f291c8d5SSiddharth Bhat   /// Check if the basic block contains a function we cannot codegen for GPU
2866f291c8d5SSiddharth Bhat   /// kernels.
2867f291c8d5SSiddharth Bhat   ///
2868f291c8d5SSiddharth Bhat   /// If this basic block does something with a `Function` other than calling
2869f291c8d5SSiddharth Bhat   /// a function that we support in a kernel, return true.
2870f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) {
2871f291c8d5SSiddharth Bhat     for (const Instruction &Inst : *BB) {
2872f291c8d5SSiddharth Bhat       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2873f291c8d5SSiddharth Bhat       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2874f291c8d5SSiddharth Bhat         continue;
2875f291c8d5SSiddharth Bhat       }
2876f291c8d5SSiddharth Bhat 
2877bccaea57SSiddharth Bhat       for (Value *SrcVal : Inst.operands()) {
2878bccaea57SSiddharth Bhat         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2879bccaea57SSiddharth Bhat         if (!p)
2880bccaea57SSiddharth Bhat           continue;
2881bccaea57SSiddharth Bhat         if (isa<FunctionType>(p->getElementType()))
2882bccaea57SSiddharth Bhat           return true;
2883bccaea57SSiddharth Bhat       }
2884f291c8d5SSiddharth Bhat     }
2885bccaea57SSiddharth Bhat     return false;
2886bccaea57SSiddharth Bhat   }
2887bccaea57SSiddharth Bhat 
2888f291c8d5SSiddharth Bhat   /// Return whether the Scop S uses functions in a way that we do not support.
2889f291c8d5SSiddharth Bhat   bool containsInvalidKernelFunction(const Scop &S) {
2890bccaea57SSiddharth Bhat     for (auto &Stmt : S) {
2891bccaea57SSiddharth Bhat       if (Stmt.isBlockStmt()) {
2892f291c8d5SSiddharth Bhat         if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock()))
2893bccaea57SSiddharth Bhat           return true;
2894bccaea57SSiddharth Bhat       } else {
2895bccaea57SSiddharth Bhat         assert(Stmt.isRegionStmt() &&
2896bccaea57SSiddharth Bhat                "Stmt was neither block nor region statement");
2897bccaea57SSiddharth Bhat         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2898f291c8d5SSiddharth Bhat           if (containsInvalidKernelFunctionInBllock(BB))
2899bccaea57SSiddharth Bhat             return true;
2900bccaea57SSiddharth Bhat       }
2901bccaea57SSiddharth Bhat     }
2902bccaea57SSiddharth Bhat     return false;
2903bccaea57SSiddharth Bhat   }
2904bccaea57SSiddharth Bhat 
290538fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
290638fc0aedSTobias Grosser   ///
290732837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
290832837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
290932837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
291038fc0aedSTobias Grosser     ScopAnnotator Annotator;
291138fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
291238fc0aedSTobias Grosser 
291338fc0aedSTobias Grosser     Region *R = &S->getRegion();
291438fc0aedSTobias Grosser 
291538fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
291638fc0aedSTobias Grosser 
291738fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
291838fc0aedSTobias Grosser 
291938fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
292038fc0aedSTobias Grosser 
292138fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
292238fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
292338fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
292438fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
292538fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
292638fc0aedSTobias Grosser     // code generating this scop.
2927256070d8SAndreas Simbuerger     BBPair StartExitBlocks =
29282d950f36SPhilip Pfaffe         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
2929256070d8SAndreas Simbuerger     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
293038fc0aedSTobias Grosser 
29312d950f36SPhilip Pfaffe     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
293217f01968SSiddharth Bhat                                StartBlock, Prog, Runtime, Architecture);
2933acf80064SEli Friedman 
293438fc0aedSTobias Grosser     // TODO: Handle LICM
293538fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
293638fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
293738fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
2938cb1aef8dSTobias Grosser 
2939cb1aef8dSTobias Grosser     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
29402b852e2eSPhilip Pfaffe     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
294182f2af35STobias Grosser     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
294282f2af35STobias Grosser     Condition = isl_ast_expr_and(Condition, SufficientCompute);
2943cb1aef8dSTobias Grosser     isl_ast_build_free(Build);
2944cb1aef8dSTobias Grosser 
2945cb1aef8dSTobias Grosser     Value *RTC = NodeBuilder.createRTC(Condition);
2946cb1aef8dSTobias Grosser     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
2947cb1aef8dSTobias Grosser 
294838fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
2949fa7b0802STobias Grosser 
2950fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
295138fc0aedSTobias Grosser     NodeBuilder.create(Root);
29528ed5e599STobias Grosser     NodeBuilder.finalize();
29535857b701STobias Grosser 
2954bc653f20STobias Grosser     /// In case a sequential kernel has more surrounding loops as any parallel
2955bc653f20STobias Grosser     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
2956de244eb4STobias Grosser     /// point in running it on a GPU.
2957bc653f20STobias Grosser     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
2958bc653f20STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
2959bc653f20STobias Grosser 
29605857b701STobias Grosser     if (!NodeBuilder.BuildSuccessful)
29615857b701STobias Grosser       SplitBlock->getTerminator()->setOperand(0, Builder.getFalse());
296238fc0aedSTobias Grosser   }
296338fc0aedSTobias Grosser 
2964e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2965e938517eSTobias Grosser     S = &CurrentScop;
296638fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
296738fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
296838fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
29697b5a4dfdSTobias Grosser     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
297038fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2971e938517eSTobias Grosser 
2972f291c8d5SSiddharth Bhat     // We currently do not support functions other than intrinsics inside
2973f291c8d5SSiddharth Bhat     // kernels, as code generation will need to offload function calls to the
2974f291c8d5SSiddharth Bhat     // kernel. This may lead to a kernel trying to call a function on the host.
2975bccaea57SSiddharth Bhat     // This also allows us to prevent codegen from trying to take the
2976bccaea57SSiddharth Bhat     // address of an intrinsic function to send to the kernel.
2977f291c8d5SSiddharth Bhat     if (containsInvalidKernelFunction(CurrentScop)) {
2978f291c8d5SSiddharth Bhat       DEBUG(
2979f291c8d5SSiddharth Bhat           dbgs()
2980f291c8d5SSiddharth Bhat               << "Scop contains function which cannot be materialised in a GPU "
2981f291c8d5SSiddharth Bhat                  "kernel. Bailing out.\n";);
2982bccaea57SSiddharth Bhat       return false;
2983f291c8d5SSiddharth Bhat     }
2984bccaea57SSiddharth Bhat 
2985e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2986e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2987f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
298838fc0aedSTobias Grosser 
298902ca346eSSingapuram Sanjay Srivallabh     if (PPCGGen->tree) {
299032837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
299102ca346eSSingapuram Sanjay Srivallabh       CurrentScop.markAsToBeSkipped();
299202ca346eSSingapuram Sanjay Srivallabh     }
299338fc0aedSTobias Grosser 
2994b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2995f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2996e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2997e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2998e938517eSTobias Grosser 
2999e938517eSTobias Grosser     return true;
3000e938517eSTobias Grosser   }
30019dfe4e7cSTobias Grosser 
30029dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
30039dfe4e7cSTobias Grosser 
30049dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
30059dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
30069dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
30079dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
30085cc87e3aSPhilip Pfaffe     AU.addRequired<ScopDetectionWrapperPass>();
30099dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
30109dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
30119dfe4e7cSTobias Grosser 
30129dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
30139dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
30149dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
30159dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
30169dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
30175cc87e3aSPhilip Pfaffe     AU.addPreserved<ScopDetectionWrapperPass>();
30189dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
30199dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
30209dfe4e7cSTobias Grosser 
30219dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
30229dfe4e7cSTobias Grosser     //        region tree.
30239dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
30249dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
30259dfe4e7cSTobias Grosser   }
30269dfe4e7cSTobias Grosser };
302724222c73STobias Grosser } // namespace
30289dfe4e7cSTobias Grosser 
30299dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
30309dfe4e7cSTobias Grosser 
303117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
303217f01968SSiddharth Bhat   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
303317f01968SSiddharth Bhat   generator->Runtime = Runtime;
303417f01968SSiddharth Bhat   generator->Architecture = Arch;
303517f01968SSiddharth Bhat   return generator;
303617f01968SSiddharth Bhat }
30379dfe4e7cSTobias Grosser 
30389dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
30399dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
30409dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
30419dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
30429dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
30439dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
30449dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
30455cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
30469dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
30479dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
3048