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 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
209dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
219dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
229dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
239dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
269dfe4e7cSTobias Grosser 
27f384594dSTobias Grosser #include "isl/union_map.h"
28f384594dSTobias Grosser 
29e938517eSTobias Grosser extern "C" {
30a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
31a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
32a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
33a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
34a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
35e938517eSTobias Grosser }
36e938517eSTobias Grosser 
379dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
389dfe4e7cSTobias Grosser 
399dfe4e7cSTobias Grosser using namespace polly;
409dfe4e7cSTobias Grosser using namespace llvm;
419dfe4e7cSTobias Grosser 
429dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
439dfe4e7cSTobias Grosser 
44f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
45f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
46681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
47f384594dSTobias Grosser                                   cl::cat(PollyCategory));
4869b46751STobias Grosser 
4969b46751STobias Grosser static cl::opt<bool>
5069b46751STobias Grosser     DumpCode("polly-acc-dump-code",
5169b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
5269b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
5369b46751STobias Grosser 
5432837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
5532837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
5632837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
5732837fe3STobias Grosser                                   cl::cat(PollyCategory));
5832837fe3STobias Grosser 
5960c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
6060c60025STobias Grosser ///
6160c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
6260c60025STobias Grosser /// of the scheduled ScopStmts.
6360c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
6460c60025STobias Grosser     void *Stmt, isl_ast_build *Build,
6560c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
6660c60025STobias Grosser                                        isl_id *Id, void *User),
6760c60025STobias Grosser     void *UserIndex,
6860c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
6960c60025STobias Grosser     void *User_expr) {
7060c60025STobias Grosser 
7160c60025STobias Grosser   // TODO: Implement the AST expression generation. For now we just return a
7260c60025STobias Grosser   // nullptr to ensure that we do not free uninitialized pointers.
7360c60025STobias Grosser 
7460c60025STobias Grosser   return nullptr;
7560c60025STobias Grosser }
76f384594dSTobias Grosser 
7738fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
7838fc0aedSTobias Grosser ///
7938fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
8038fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
8138fc0aedSTobias Grosser /// for generating GPU specific user nodes.
8238fc0aedSTobias Grosser ///
8338fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
8438fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
8538fc0aedSTobias Grosser public:
8638fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
8738fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
8832837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
8932837fe3STobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {}
9038fc0aedSTobias Grosser 
9138fc0aedSTobias Grosser private:
9232837fe3STobias Grosser   /// A module containing GPU code.
9332837fe3STobias Grosser   ///
9432837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
9532837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
9632837fe3STobias Grosser 
9732837fe3STobias Grosser   /// The GPU program we generate code for.
9832837fe3STobias Grosser   gpu_prog *Prog;
9932837fe3STobias Grosser 
100472f9654STobias Grosser   /// Class to free isl_ids.
101472f9654STobias Grosser   class IslIdDeleter {
102472f9654STobias Grosser   public:
103472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
104472f9654STobias Grosser   };
105472f9654STobias Grosser 
106472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
107472f9654STobias Grosser   ///
108472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
109472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
110472f9654STobias Grosser 
11138fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
11238fc0aedSTobias Grosser   ///
11338fc0aedSTobias Grosser   /// These AST nodes can be of type:
11438fc0aedSTobias Grosser   ///
11538fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
11638fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
11738fc0aedSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer (TODO)
11838fc0aedSTobias Grosser   ///
1191fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1201fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
12132837fe3STobias Grosser 
12232837fe3STobias Grosser   /// Create GPU kernel.
12332837fe3STobias Grosser   ///
12432837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
12532837fe3STobias Grosser   ///
12632837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
12732837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
12832837fe3STobias Grosser 
12932837fe3STobias Grosser   /// Create kernel function.
13032837fe3STobias Grosser   ///
13132837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
13232837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
13332837fe3STobias Grosser   /// start block of this newly created function.
13432837fe3STobias Grosser   ///
13532837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
13632837fe3STobias Grosser   void createKernelFunction(ppcg_kernel *Kernel);
13732837fe3STobias Grosser 
13832837fe3STobias Grosser   /// Create the declaration of a kernel function.
13932837fe3STobias Grosser   ///
14032837fe3STobias Grosser   /// The kernel function takes as arguments:
14132837fe3STobias Grosser   ///
14232837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
143*f6044bd0STobias Grosser   ///   - Host iterators
14432837fe3STobias Grosser   ///   - Parameters (TODO)
14532837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
14632837fe3STobias Grosser   ///
14732837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
14832837fe3STobias Grosser   /// @returns The newly declared function.
14932837fe3STobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel);
15032837fe3STobias Grosser 
151472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
152472f9654STobias Grosser   ///
153472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
154472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
155472f9654STobias Grosser 
15632837fe3STobias Grosser   /// Finalize the generation of the kernel function.
15732837fe3STobias Grosser   ///
15832837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
15932837fe3STobias Grosser   /// dump its IR to stderr.
16032837fe3STobias Grosser   void finalizeKernelFunction();
1611fb9b64dSTobias Grosser };
1621fb9b64dSTobias Grosser 
1631fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
16432837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
16532837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
16632837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
16732837fe3STobias Grosser   isl_id_free(Id);
16832837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
16932837fe3STobias Grosser 
17032837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
17132837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
17232837fe3STobias Grosser     createKernel(UserStmt);
17332837fe3STobias Grosser     isl_ast_expr_free(Expr);
17432837fe3STobias Grosser     return;
17532837fe3STobias Grosser   }
17632837fe3STobias Grosser 
17732837fe3STobias Grosser   isl_ast_expr_free(Expr);
1781fb9b64dSTobias Grosser   isl_ast_node_free(UserStmt);
17938fc0aedSTobias Grosser   return;
18038fc0aedSTobias Grosser }
18138fc0aedSTobias Grosser 
18232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
18332837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
18432837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
18532837fe3STobias Grosser   isl_id_free(Id);
18632837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
18732837fe3STobias Grosser 
18832837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
18932837fe3STobias Grosser 
19032837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
191472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
19232837fe3STobias Grosser 
19332837fe3STobias Grosser   createKernelFunction(Kernel);
19432837fe3STobias Grosser 
19532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
196472f9654STobias Grosser   IDToValue = HostIDs;
19732837fe3STobias Grosser 
19832837fe3STobias Grosser   finalizeKernelFunction();
19932837fe3STobias Grosser }
20032837fe3STobias Grosser 
20132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
20232837fe3STobias Grosser ///
20332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
20432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
20532837fe3STobias Grosser   std::string Ret = "e";
20632837fe3STobias Grosser 
20732837fe3STobias Grosser   if (!is64Bit)
20832837fe3STobias Grosser     Ret += "-p:32:32";
20932837fe3STobias Grosser 
21032837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
21132837fe3STobias Grosser 
21232837fe3STobias Grosser   return Ret;
21332837fe3STobias Grosser }
21432837fe3STobias Grosser 
21532837fe3STobias Grosser Function *GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel) {
21632837fe3STobias Grosser   std::vector<Type *> Args;
21732837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
21832837fe3STobias Grosser 
21932837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
22032837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
22132837fe3STobias Grosser       continue;
22232837fe3STobias Grosser 
22332837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
22432837fe3STobias Grosser   }
22532837fe3STobias Grosser 
226*f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
227*f6044bd0STobias Grosser 
228*f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
229*f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
230*f6044bd0STobias Grosser 
23132837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
23232837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
23332837fe3STobias Grosser                               GPUModule.get());
23432837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
23532837fe3STobias Grosser 
23632837fe3STobias Grosser   auto Arg = FN->arg_begin();
23732837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
23832837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
23932837fe3STobias Grosser       continue;
24032837fe3STobias Grosser 
24132837fe3STobias Grosser     Arg->setName(Prog->array[i].name);
24232837fe3STobias Grosser     Arg++;
24332837fe3STobias Grosser   }
24432837fe3STobias Grosser 
245*f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
246*f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
247*f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
248*f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
249*f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
250*f6044bd0STobias Grosser     Arg++;
251*f6044bd0STobias Grosser   }
252*f6044bd0STobias Grosser 
25332837fe3STobias Grosser   return FN;
25432837fe3STobias Grosser }
25532837fe3STobias Grosser 
256472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
257472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
258472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
259472f9654STobias Grosser 
260472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
261472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
262472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
263472f9654STobias Grosser 
264472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
265472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
266472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
267472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
268472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
269472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
270472f9654STobias Grosser     IDToValue[Id] = Val;
271472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
272472f9654STobias Grosser   };
273472f9654STobias Grosser 
274472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
275472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
276472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
277472f9654STobias Grosser   }
278472f9654STobias Grosser 
279472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
280472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
281472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
282472f9654STobias Grosser   }
283472f9654STobias Grosser }
284472f9654STobias Grosser 
28532837fe3STobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel) {
28632837fe3STobias Grosser 
28732837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
28832837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
28932837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
29032837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
29132837fe3STobias Grosser 
29232837fe3STobias Grosser   Function *FN = createKernelFunctionDecl(Kernel);
29332837fe3STobias Grosser 
29432837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
29532837fe3STobias Grosser 
29632837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
29732837fe3STobias Grosser   Builder.CreateRetVoid();
29832837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
299472f9654STobias Grosser 
300472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
30132837fe3STobias Grosser }
30232837fe3STobias Grosser 
30332837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
30432837fe3STobias Grosser 
30532837fe3STobias Grosser   if (DumpKernelIR)
30632837fe3STobias Grosser     outs() << *GPUModule << "\n";
30732837fe3STobias Grosser 
30832837fe3STobias Grosser   GPUModule.release();
309472f9654STobias Grosser   KernelIDs.clear();
31032837fe3STobias Grosser }
31132837fe3STobias Grosser 
3129dfe4e7cSTobias Grosser namespace {
3139dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
3149dfe4e7cSTobias Grosser public:
3159dfe4e7cSTobias Grosser   static char ID;
3169dfe4e7cSTobias Grosser 
317e938517eSTobias Grosser   /// The scop that is currently processed.
318e938517eSTobias Grosser   Scop *S;
319e938517eSTobias Grosser 
32038fc0aedSTobias Grosser   LoopInfo *LI;
32138fc0aedSTobias Grosser   DominatorTree *DT;
32238fc0aedSTobias Grosser   ScalarEvolution *SE;
32338fc0aedSTobias Grosser   const DataLayout *DL;
32438fc0aedSTobias Grosser   RegionInfo *RI;
32538fc0aedSTobias Grosser 
3269dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
3279dfe4e7cSTobias Grosser 
328e938517eSTobias Grosser   /// Construct compilation options for PPCG.
329e938517eSTobias Grosser   ///
330e938517eSTobias Grosser   /// @returns The compilation options.
331e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
332e938517eSTobias Grosser     auto DebugOptions =
333e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
334e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
335e938517eSTobias Grosser 
336e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
337e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
338e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
339e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
340e938517eSTobias Grosser 
341e938517eSTobias Grosser     Options->debug = DebugOptions;
342e938517eSTobias Grosser 
343e938517eSTobias Grosser     Options->reschedule = true;
344e938517eSTobias Grosser     Options->scale_tile_loops = false;
345e938517eSTobias Grosser     Options->wrap = false;
346e938517eSTobias Grosser 
347e938517eSTobias Grosser     Options->non_negative_parameters = false;
348e938517eSTobias Grosser     Options->ctx = nullptr;
349e938517eSTobias Grosser     Options->sizes = nullptr;
350e938517eSTobias Grosser 
3514eaedde5STobias Grosser     Options->tile_size = 32;
3524eaedde5STobias Grosser 
353e938517eSTobias Grosser     Options->use_private_memory = false;
354e938517eSTobias Grosser     Options->use_shared_memory = false;
355e938517eSTobias Grosser     Options->max_shared_memory = 0;
356e938517eSTobias Grosser 
357e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
358e938517eSTobias Grosser     Options->openmp = false;
359e938517eSTobias Grosser     Options->linearize_device_arrays = true;
360e938517eSTobias Grosser     Options->live_range_reordering = false;
361e938517eSTobias Grosser 
362e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
363e938517eSTobias Grosser     Options->opencl_use_gpu = false;
364e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
365e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
366e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
367e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
368e938517eSTobias Grosser 
369e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
370e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
371e938517eSTobias Grosser 
372e938517eSTobias Grosser     return Options;
373e938517eSTobias Grosser   }
374e938517eSTobias Grosser 
375f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
376f384594dSTobias Grosser   ///
377f384594dSTobias Grosser   /// Instead of a normal access of the form:
378f384594dSTobias Grosser   ///
379f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
380f384594dSTobias Grosser   ///
381f384594dSTobias Grosser   /// a tagged access has the form
382f384594dSTobias Grosser   ///
383f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
384f384594dSTobias Grosser   ///
385f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
386f384594dSTobias Grosser   /// triggered the access.
387f384594dSTobias Grosser   ///
388f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
389f384594dSTobias Grosser   ///
390f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
391f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
392f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
393f384594dSTobias Grosser 
394f384594dSTobias Grosser     for (auto &Stmt : *S)
395f384594dSTobias Grosser       for (auto &Acc : Stmt)
396f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
397f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
398f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
399f384594dSTobias Grosser 
400f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
401f384594dSTobias Grosser           Space = isl_space_range(Space);
402f384594dSTobias Grosser           Space = isl_space_from_range(Space);
4036293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
404f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
405f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
406f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
407f384594dSTobias Grosser         }
408f384594dSTobias Grosser 
409f384594dSTobias Grosser     return Accesses;
410f384594dSTobias Grosser   }
411f384594dSTobias Grosser 
412f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
413f384594dSTobias Grosser   ///
414f384594dSTobias Grosser   /// @see getTaggedAccesses
415f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
416f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
417f384594dSTobias Grosser   }
418f384594dSTobias Grosser 
419f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
420f384594dSTobias Grosser   ///
421f384594dSTobias Grosser   /// @see getTaggedAccesses
422f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
423f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
424f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
425f384594dSTobias Grosser   }
426f384594dSTobias Grosser 
427f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
428f384594dSTobias Grosser   ///
429f384594dSTobias Grosser   /// @see getTaggedAccesses
430f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
431f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
432f384594dSTobias Grosser   }
433f384594dSTobias Grosser 
434aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
435aef5196fSTobias Grosser   ///
436aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
437aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
438aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
439aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
440aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
441aef5196fSTobias Grosser   /// the data format that ppcg expects.
442aef5196fSTobias Grosser   ///
443aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
444aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
445aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
446bd81a7eeSTobias Grosser         S->getIslCtx(),
447bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
448aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
449aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
450aef5196fSTobias Grosser 
451aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
452aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
453aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
454aef5196fSTobias Grosser     }
455aef5196fSTobias Grosser 
456aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
457aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
458aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
459aef5196fSTobias Grosser     }
460aef5196fSTobias Grosser 
461aef5196fSTobias Grosser     isl_space_free(Space);
462aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
463aef5196fSTobias Grosser 
464aef5196fSTobias Grosser     return Names;
465aef5196fSTobias Grosser   }
466aef5196fSTobias Grosser 
467e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
468e938517eSTobias Grosser   ///
469f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
470f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
471f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
472f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
473e938517eSTobias Grosser   ///
474e938517eSTobias Grosser   /// @returns A new ppcg scop.
475e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
476e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
477e938517eSTobias Grosser 
478e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
479e938517eSTobias Grosser 
480e938517eSTobias Grosser     PPCGScop->start = 0;
481e938517eSTobias Grosser     PPCGScop->end = 0;
482e938517eSTobias Grosser 
483f384594dSTobias Grosser     PPCGScop->context = S->getContext();
484f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
485e938517eSTobias Grosser     PPCGScop->call = nullptr;
486f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
487f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
488e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
489f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
490f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
491f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
492f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
493e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
494f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
495e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
496e938517eSTobias Grosser 
497e938517eSTobias Grosser     PPCGScop->independence = nullptr;
498e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
499e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
500e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
501e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
502e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
503e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
504e938517eSTobias Grosser 
505f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
506aef5196fSTobias Grosser     PPCGScop->names = getNames();
507e938517eSTobias Grosser 
508e938517eSTobias Grosser     PPCGScop->pet = nullptr;
509e938517eSTobias Grosser 
510f384594dSTobias Grosser     compute_tagger(PPCGScop);
511f384594dSTobias Grosser     compute_dependences(PPCGScop);
512f384594dSTobias Grosser 
513e938517eSTobias Grosser     return PPCGScop;
514e938517eSTobias Grosser   }
515e938517eSTobias Grosser 
51660f63b49STobias Grosser   /// Collect the array acesses in a statement.
51760f63b49STobias Grosser   ///
51860f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
51960f63b49STobias Grosser   ///
52060f63b49STobias Grosser   /// @returns A list of array accesses.
52160f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
52260f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
52360f63b49STobias Grosser 
52460f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
52560f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
52660f63b49STobias Grosser       Access->read = Acc->isRead();
52760f63b49STobias Grosser       Access->write = Acc->isWrite();
52860f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
52960f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
53060f63b49STobias Grosser       Space = isl_space_range(Space);
53160f63b49STobias Grosser       Space = isl_space_from_range(Space);
5326293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
53360f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
53460f63b49STobias Grosser       Access->tagged_access =
53560f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
53660f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
53760f63b49STobias Grosser       Access->ref_id = Acc->getId();
53860f63b49STobias Grosser       Access->next = Accesses;
53960f63b49STobias Grosser       Accesses = Access;
54060f63b49STobias Grosser     }
54160f63b49STobias Grosser 
54260f63b49STobias Grosser     return Accesses;
54360f63b49STobias Grosser   }
54460f63b49STobias Grosser 
54569b46751STobias Grosser   /// Collect the list of GPU statements.
54669b46751STobias Grosser   ///
54769b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
54869b46751STobias Grosser   /// as well as a list with all memory accesses.
54969b46751STobias Grosser   ///
55069b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
55169b46751STobias Grosser   ///
55269b46751STobias Grosser   /// @returns A linked-list of statements.
55369b46751STobias Grosser   gpu_stmt *getStatements() {
55469b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
55569b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
55669b46751STobias Grosser 
55769b46751STobias Grosser     int i = 0;
55869b46751STobias Grosser     for (auto &Stmt : *S) {
55969b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
56069b46751STobias Grosser 
56169b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
56269b46751STobias Grosser 
56369b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
56469b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
56560f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
56669b46751STobias Grosser       i++;
56769b46751STobias Grosser     }
56869b46751STobias Grosser 
56969b46751STobias Grosser     return Stmts;
57069b46751STobias Grosser   }
57169b46751STobias Grosser 
57260f63b49STobias Grosser   /// Derive the extent of an array.
57360f63b49STobias Grosser   ///
57460f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
57560f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
57660f63b49STobias Grosser   ///
57760f63b49STobias Grosser   /// @param Array The array to derive the extent for.
57860f63b49STobias Grosser   ///
57960f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
58060f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
58160f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
58260f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
58360f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
58460f63b49STobias Grosser     isl_set *AccessSet =
58560f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
58660f63b49STobias Grosser     isl_union_set_free(AccessUSet);
58760f63b49STobias Grosser 
58860f63b49STobias Grosser     return AccessSet;
58960f63b49STobias Grosser   }
59060f63b49STobias Grosser 
59160f63b49STobias Grosser   /// Derive the bounds of an array.
59260f63b49STobias Grosser   ///
59360f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
59460f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
59560f63b49STobias Grosser   /// ScopArrayInfo.
59660f63b49STobias Grosser   ///
59760f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
59860f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
59960f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
60060f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
60160f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
60260f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
60360f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
60460f63b49STobias Grosser       isl_set_free(Dom);
60560f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
60660f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
60760f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
60860f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
60960f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
61060f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
61160f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
61260f63b49STobias Grosser     }
61360f63b49STobias Grosser 
61460f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
61560f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
61660f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
61760f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
61860f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
61960f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
62060f63b49STobias Grosser     }
62160f63b49STobias Grosser   }
62260f63b49STobias Grosser 
62360f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
62460f63b49STobias Grosser   ///
62560f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
62660f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
62760f63b49STobias Grosser     int i = 0;
62860f63b49STobias Grosser     for (auto &Element : S->arrays()) {
62960f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
63060f63b49STobias Grosser 
63160f63b49STobias Grosser       std::string TypeName;
63260f63b49STobias Grosser       raw_string_ostream OS(TypeName);
63360f63b49STobias Grosser 
63460f63b49STobias Grosser       OS << *Array->getElementType();
63560f63b49STobias Grosser       TypeName = OS.str();
63660f63b49STobias Grosser 
63760f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
63860f63b49STobias Grosser 
63960f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
64060f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
64160f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
64260f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
64360f63b49STobias Grosser       PPCGArray.extent = nullptr;
64460f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
64560f63b49STobias Grosser       PPCGArray.bound =
64660f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
64760f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
64860f63b49STobias Grosser       PPCGArray.n_ref = 0;
64960f63b49STobias Grosser       PPCGArray.refs = nullptr;
65060f63b49STobias Grosser       PPCGArray.accessed = true;
65160f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
65260f63b49STobias Grosser       PPCGArray.has_compound_element = false;
65360f63b49STobias Grosser       PPCGArray.local = false;
65460f63b49STobias Grosser       PPCGArray.declare_local = false;
65560f63b49STobias Grosser       PPCGArray.global = false;
65660f63b49STobias Grosser       PPCGArray.linearize = false;
65760f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
65860f63b49STobias Grosser 
65960f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
6602d010dafSTobias Grosser       i++;
661b9fc860aSTobias Grosser 
662b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
66360f63b49STobias Grosser     }
66460f63b49STobias Grosser   }
66560f63b49STobias Grosser 
66660f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
66760f63b49STobias Grosser   ///
66860f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
66960f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
67060f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
67160f63b49STobias Grosser 
67260f63b49STobias Grosser     for (auto &Item : S->arrays()) {
67360f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
67460f63b49STobias Grosser       isl_space *Space = Array->getSpace();
67560f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
67660f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
67760f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
67860f63b49STobias Grosser     }
67960f63b49STobias Grosser 
68060f63b49STobias Grosser     return Maps;
68160f63b49STobias Grosser   }
68260f63b49STobias Grosser 
683e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
684e938517eSTobias Grosser   ///
685e938517eSTobias Grosser   /// @returns A new gpu grogram description.
686e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
687e938517eSTobias Grosser 
688e938517eSTobias Grosser     if (!PPCGScop)
689e938517eSTobias Grosser       return nullptr;
690e938517eSTobias Grosser 
691e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
692e938517eSTobias Grosser 
693e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
694e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
695aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
69660f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
69760f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
69860f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
69960f63b49STobias Grosser     PPCGProg->tagged_must_kill =
70060f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
70160f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
70260f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
70360f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
704e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
705e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
70669b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
70769b46751STobias Grosser     PPCGProg->stmts = getStatements();
70860f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
70960f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
71060f63b49STobias Grosser                                        PPCGProg->n_array);
71160f63b49STobias Grosser 
71260f63b49STobias Grosser     createArrays(PPCGProg);
713e938517eSTobias Grosser 
714e938517eSTobias Grosser     return PPCGProg;
715e938517eSTobias Grosser   }
716e938517eSTobias Grosser 
71769b46751STobias Grosser   struct PrintGPUUserData {
71869b46751STobias Grosser     struct cuda_info *CudaInfo;
71969b46751STobias Grosser     struct gpu_prog *PPCGProg;
72069b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
72169b46751STobias Grosser   };
72269b46751STobias Grosser 
72369b46751STobias Grosser   /// Print a user statement node in the host code.
72469b46751STobias Grosser   ///
72569b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
72669b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
72769b46751STobias Grosser   /// host ast.
72869b46751STobias Grosser   ///
72969b46751STobias Grosser   /// @param P The printer to print to
73069b46751STobias Grosser   /// @param Options The printing options to use
73169b46751STobias Grosser   /// @param Node The node to print
73269b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
73369b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
73469b46751STobias Grosser   ///
73569b46751STobias Grosser   /// @returns A printer to which the output has been printed.
73669b46751STobias Grosser   static __isl_give isl_printer *
73769b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
73869b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
73969b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
74069b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
74169b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
74269b46751STobias Grosser 
74369b46751STobias Grosser     if (Id) {
74420251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
74520251734STobias Grosser 
74620251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
74720251734STobias Grosser       // otherwise try to call pet functionality that is not available in
74820251734STobias Grosser       // Polly.
74920251734STobias Grosser       if (IsUser) {
75020251734STobias Grosser         P = isl_printer_start_line(P);
75120251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
75220251734STobias Grosser         P = isl_printer_end_line(P);
75320251734STobias Grosser         isl_id_free(Id);
75420251734STobias Grosser         isl_ast_print_options_free(Options);
75520251734STobias Grosser         return P;
75620251734STobias Grosser       }
75720251734STobias Grosser 
75869b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
75969b46751STobias Grosser       isl_id_free(Id);
76069b46751STobias Grosser       Data->Kernels.push_back(Kernel);
76169b46751STobias Grosser     }
76269b46751STobias Grosser 
76369b46751STobias Grosser     return print_host_user(P, Options, Node, User);
76469b46751STobias Grosser   }
76569b46751STobias Grosser 
76669b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
76769b46751STobias Grosser   ///
76869b46751STobias Grosser   /// @param Kernel The kernel to print
76969b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
77069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
77169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
77269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
77369b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
77469b46751STobias Grosser     char *String = isl_printer_get_str(P);
77569b46751STobias Grosser     printf("%s\n", String);
77669b46751STobias Grosser     free(String);
77769b46751STobias Grosser     isl_printer_free(P);
77869b46751STobias Grosser   }
77969b46751STobias Grosser 
78069b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
78169b46751STobias Grosser   ///
78269b46751STobias Grosser   /// @param Tree An AST describing GPU code
78369b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
78469b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
78569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
78669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
78769b46751STobias Grosser 
78869b46751STobias Grosser     PrintGPUUserData Data;
78969b46751STobias Grosser     Data.PPCGProg = PPCGProg;
79069b46751STobias Grosser 
79169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
79269b46751STobias Grosser     Options =
79369b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
79469b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
79569b46751STobias Grosser     char *String = isl_printer_get_str(P);
79669b46751STobias Grosser     printf("# host\n");
79769b46751STobias Grosser     printf("%s\n", String);
79869b46751STobias Grosser     free(String);
79969b46751STobias Grosser     isl_printer_free(P);
80069b46751STobias Grosser 
80169b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
80269b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
80369b46751STobias Grosser       printKernel(Kernel);
80469b46751STobias Grosser     }
80569b46751STobias Grosser   }
80669b46751STobias Grosser 
807f384594dSTobias Grosser   // Generate a GPU program using PPCG.
808f384594dSTobias Grosser   //
809f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
810f384594dSTobias Grosser   //
811f384594dSTobias Grosser   //  1) Compute new schedule for the program.
812f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
813f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
814f384594dSTobias Grosser   //
815f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
816f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
817f384594dSTobias Grosser   // strategy directly from this pass.
818f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
819f384594dSTobias Grosser 
820f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
821f384594dSTobias Grosser 
822f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
823f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
824f384594dSTobias Grosser     PPCGGen->print = nullptr;
825f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
82660c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
827f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
828f384594dSTobias Grosser     PPCGGen->tree = nullptr;
829f384594dSTobias Grosser     PPCGGen->types.n = 0;
830f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
831f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
832f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
833f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
834f384594dSTobias Grosser 
835f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
836f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
837f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
8382341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
839f384594dSTobias Grosser 
840f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
841f384594dSTobias Grosser 
842aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
843aef5196fSTobias Grosser 
84469b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
845aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
84669b46751STobias Grosser     } else {
847aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
84869b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
84969b46751STobias Grosser     }
850aef5196fSTobias Grosser 
851f384594dSTobias Grosser     if (DumpSchedule) {
852f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
853f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
854f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
855f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
856f384594dSTobias Grosser       if (Schedule)
857f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
858f384594dSTobias Grosser       else
859f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
860f384594dSTobias Grosser 
861f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
862f384594dSTobias Grosser       isl_printer_free(P);
863f384594dSTobias Grosser     }
864f384594dSTobias Grosser 
86569b46751STobias Grosser     if (DumpCode) {
86669b46751STobias Grosser       printf("Code\n");
86769b46751STobias Grosser       printf("====\n");
86869b46751STobias Grosser       if (PPCGGen->tree)
86969b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
87069b46751STobias Grosser       else
87169b46751STobias Grosser         printf("No code generated\n");
87269b46751STobias Grosser     }
87369b46751STobias Grosser 
874f384594dSTobias Grosser     isl_schedule_free(Schedule);
875f384594dSTobias Grosser 
876f384594dSTobias Grosser     return PPCGGen;
877f384594dSTobias Grosser   }
878f384594dSTobias Grosser 
879f384594dSTobias Grosser   /// Free gpu_gen structure.
880f384594dSTobias Grosser   ///
881f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
882f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
883f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
884f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
885f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
886f384594dSTobias Grosser     free(PPCGGen);
887f384594dSTobias Grosser   }
888f384594dSTobias Grosser 
889b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
890b307ed4dSTobias Grosser   ///
891b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
892b307ed4dSTobias Grosser   /// ourselves.
893b307ed4dSTobias Grosser   ///
894b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
895b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
896b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
897b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
898b307ed4dSTobias Grosser     free(PPCGScop->options);
899b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
900b307ed4dSTobias Grosser   }
901b307ed4dSTobias Grosser 
90238fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
90338fc0aedSTobias Grosser   ///
90432837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
90532837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
90632837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
90738fc0aedSTobias Grosser     ScopAnnotator Annotator;
90838fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
90938fc0aedSTobias Grosser 
91038fc0aedSTobias Grosser     Region *R = &S->getRegion();
91138fc0aedSTobias Grosser 
91238fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
91338fc0aedSTobias Grosser 
91438fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
91538fc0aedSTobias Grosser 
91638fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
91738fc0aedSTobias Grosser 
91832837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
91932837fe3STobias Grosser                                Prog);
92038fc0aedSTobias Grosser 
92138fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
92238fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
92338fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
92438fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
92538fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
92638fc0aedSTobias Grosser     // code generating this scop.
92738fc0aedSTobias Grosser     BasicBlock *StartBlock =
92838fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
92938fc0aedSTobias Grosser 
93038fc0aedSTobias Grosser     // TODO: Handle LICM
93138fc0aedSTobias Grosser     // TODO: Verify run-time checks
93238fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
93338fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
93438fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
93538fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
93638fc0aedSTobias Grosser     NodeBuilder.create(Root);
93738fc0aedSTobias Grosser     NodeBuilder.finalizeSCoP(*S);
93838fc0aedSTobias Grosser   }
93938fc0aedSTobias Grosser 
940e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
941e938517eSTobias Grosser     S = &CurrentScop;
94238fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
94338fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
94438fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
94538fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
94638fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
947e938517eSTobias Grosser 
948e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
949e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
950f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
95138fc0aedSTobias Grosser 
95238fc0aedSTobias Grosser     if (PPCGGen->tree)
95332837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
95438fc0aedSTobias Grosser 
955b307ed4dSTobias Grosser     freeOptions(PPCGScop);
956f384594dSTobias Grosser     freePPCGGen(PPCGGen);
957e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
958e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
959e938517eSTobias Grosser 
960e938517eSTobias Grosser     return true;
961e938517eSTobias Grosser   }
9629dfe4e7cSTobias Grosser 
9639dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
9649dfe4e7cSTobias Grosser 
9659dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
9669dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
9679dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
9689dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
9699dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
9709dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
9719dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
9729dfe4e7cSTobias Grosser 
9739dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
9749dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
9759dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
9769dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
9779dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
9789dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
9799dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
9809dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
9819dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
9829dfe4e7cSTobias Grosser 
9839dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
9849dfe4e7cSTobias Grosser     //        region tree.
9859dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
9869dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
9879dfe4e7cSTobias Grosser   }
9889dfe4e7cSTobias Grosser };
9899dfe4e7cSTobias Grosser }
9909dfe4e7cSTobias Grosser 
9919dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
9929dfe4e7cSTobias Grosser 
9939dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
9949dfe4e7cSTobias Grosser 
9959dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
9969dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
9979dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
9989dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
9999dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
10009dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
10019dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
10029dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
10039dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
10049dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
1005