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 
100*472f9654STobias Grosser   /// Class to free isl_ids.
101*472f9654STobias Grosser   class IslIdDeleter {
102*472f9654STobias Grosser   public:
103*472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
104*472f9654STobias Grosser   };
105*472f9654STobias Grosser 
106*472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
107*472f9654STobias Grosser   ///
108*472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
109*472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
110*472f9654STobias 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.
14332837fe3STobias Grosser   ///   - Host iterators (TODO)
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 
151*472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
152*472f9654STobias Grosser   ///
153*472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
154*472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
155*472f9654STobias 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();
191*472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
19232837fe3STobias Grosser 
19332837fe3STobias Grosser   createKernelFunction(Kernel);
19432837fe3STobias Grosser 
19532837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
196*472f9654STobias 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 
22632837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
22732837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
22832837fe3STobias Grosser                               GPUModule.get());
22932837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
23032837fe3STobias Grosser 
23132837fe3STobias Grosser   auto Arg = FN->arg_begin();
23232837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
23332837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
23432837fe3STobias Grosser       continue;
23532837fe3STobias Grosser 
23632837fe3STobias Grosser     Arg->setName(Prog->array[i].name);
23732837fe3STobias Grosser     Arg++;
23832837fe3STobias Grosser   }
23932837fe3STobias Grosser 
24032837fe3STobias Grosser   return FN;
24132837fe3STobias Grosser }
24232837fe3STobias Grosser 
243*472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
244*472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
245*472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
246*472f9654STobias Grosser 
247*472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
248*472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
249*472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
250*472f9654STobias Grosser 
251*472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
252*472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
253*472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
254*472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
255*472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
256*472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
257*472f9654STobias Grosser     IDToValue[Id] = Val;
258*472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
259*472f9654STobias Grosser   };
260*472f9654STobias Grosser 
261*472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
262*472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
263*472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
264*472f9654STobias Grosser   }
265*472f9654STobias Grosser 
266*472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
267*472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
268*472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
269*472f9654STobias Grosser   }
270*472f9654STobias Grosser }
271*472f9654STobias Grosser 
27232837fe3STobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel) {
27332837fe3STobias Grosser 
27432837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
27532837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
27632837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
27732837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
27832837fe3STobias Grosser 
27932837fe3STobias Grosser   Function *FN = createKernelFunctionDecl(Kernel);
28032837fe3STobias Grosser 
28132837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
28232837fe3STobias Grosser 
28332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
28432837fe3STobias Grosser   Builder.CreateRetVoid();
28532837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
286*472f9654STobias Grosser 
287*472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
28832837fe3STobias Grosser }
28932837fe3STobias Grosser 
29032837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() {
29132837fe3STobias Grosser 
29232837fe3STobias Grosser   if (DumpKernelIR)
29332837fe3STobias Grosser     outs() << *GPUModule << "\n";
29432837fe3STobias Grosser 
29532837fe3STobias Grosser   GPUModule.release();
296*472f9654STobias Grosser   KernelIDs.clear();
29732837fe3STobias Grosser }
29832837fe3STobias Grosser 
2999dfe4e7cSTobias Grosser namespace {
3009dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
3019dfe4e7cSTobias Grosser public:
3029dfe4e7cSTobias Grosser   static char ID;
3039dfe4e7cSTobias Grosser 
304e938517eSTobias Grosser   /// The scop that is currently processed.
305e938517eSTobias Grosser   Scop *S;
306e938517eSTobias Grosser 
30738fc0aedSTobias Grosser   LoopInfo *LI;
30838fc0aedSTobias Grosser   DominatorTree *DT;
30938fc0aedSTobias Grosser   ScalarEvolution *SE;
31038fc0aedSTobias Grosser   const DataLayout *DL;
31138fc0aedSTobias Grosser   RegionInfo *RI;
31238fc0aedSTobias Grosser 
3139dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
3149dfe4e7cSTobias Grosser 
315e938517eSTobias Grosser   /// Construct compilation options for PPCG.
316e938517eSTobias Grosser   ///
317e938517eSTobias Grosser   /// @returns The compilation options.
318e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
319e938517eSTobias Grosser     auto DebugOptions =
320e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
321e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
322e938517eSTobias Grosser 
323e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
324e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
325e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
326e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
327e938517eSTobias Grosser 
328e938517eSTobias Grosser     Options->debug = DebugOptions;
329e938517eSTobias Grosser 
330e938517eSTobias Grosser     Options->reschedule = true;
331e938517eSTobias Grosser     Options->scale_tile_loops = false;
332e938517eSTobias Grosser     Options->wrap = false;
333e938517eSTobias Grosser 
334e938517eSTobias Grosser     Options->non_negative_parameters = false;
335e938517eSTobias Grosser     Options->ctx = nullptr;
336e938517eSTobias Grosser     Options->sizes = nullptr;
337e938517eSTobias Grosser 
3384eaedde5STobias Grosser     Options->tile_size = 32;
3394eaedde5STobias Grosser 
340e938517eSTobias Grosser     Options->use_private_memory = false;
341e938517eSTobias Grosser     Options->use_shared_memory = false;
342e938517eSTobias Grosser     Options->max_shared_memory = 0;
343e938517eSTobias Grosser 
344e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
345e938517eSTobias Grosser     Options->openmp = false;
346e938517eSTobias Grosser     Options->linearize_device_arrays = true;
347e938517eSTobias Grosser     Options->live_range_reordering = false;
348e938517eSTobias Grosser 
349e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
350e938517eSTobias Grosser     Options->opencl_use_gpu = false;
351e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
352e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
353e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
354e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
355e938517eSTobias Grosser 
356e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
357e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
358e938517eSTobias Grosser 
359e938517eSTobias Grosser     return Options;
360e938517eSTobias Grosser   }
361e938517eSTobias Grosser 
362f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
363f384594dSTobias Grosser   ///
364f384594dSTobias Grosser   /// Instead of a normal access of the form:
365f384594dSTobias Grosser   ///
366f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
367f384594dSTobias Grosser   ///
368f384594dSTobias Grosser   /// a tagged access has the form
369f384594dSTobias Grosser   ///
370f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
371f384594dSTobias Grosser   ///
372f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
373f384594dSTobias Grosser   /// triggered the access.
374f384594dSTobias Grosser   ///
375f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
376f384594dSTobias Grosser   ///
377f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
378f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
379f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
380f384594dSTobias Grosser 
381f384594dSTobias Grosser     for (auto &Stmt : *S)
382f384594dSTobias Grosser       for (auto &Acc : Stmt)
383f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
384f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
385f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
386f384594dSTobias Grosser 
387f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
388f384594dSTobias Grosser           Space = isl_space_range(Space);
389f384594dSTobias Grosser           Space = isl_space_from_range(Space);
3906293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
391f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
392f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
393f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
394f384594dSTobias Grosser         }
395f384594dSTobias Grosser 
396f384594dSTobias Grosser     return Accesses;
397f384594dSTobias Grosser   }
398f384594dSTobias Grosser 
399f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
400f384594dSTobias Grosser   ///
401f384594dSTobias Grosser   /// @see getTaggedAccesses
402f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
403f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
404f384594dSTobias Grosser   }
405f384594dSTobias Grosser 
406f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
407f384594dSTobias Grosser   ///
408f384594dSTobias Grosser   /// @see getTaggedAccesses
409f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
410f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
411f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
412f384594dSTobias Grosser   }
413f384594dSTobias Grosser 
414f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
415f384594dSTobias Grosser   ///
416f384594dSTobias Grosser   /// @see getTaggedAccesses
417f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
418f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
419f384594dSTobias Grosser   }
420f384594dSTobias Grosser 
421aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
422aef5196fSTobias Grosser   ///
423aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
424aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
425aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
426aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
427aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
428aef5196fSTobias Grosser   /// the data format that ppcg expects.
429aef5196fSTobias Grosser   ///
430aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
431aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
432aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
433bd81a7eeSTobias Grosser         S->getIslCtx(),
434bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
435aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
436aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
437aef5196fSTobias Grosser 
438aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
439aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
440aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
441aef5196fSTobias Grosser     }
442aef5196fSTobias Grosser 
443aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
444aef5196fSTobias Grosser       auto Id = Array.second->getBasePtrId();
445aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
446aef5196fSTobias Grosser     }
447aef5196fSTobias Grosser 
448aef5196fSTobias Grosser     isl_space_free(Space);
449aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
450aef5196fSTobias Grosser 
451aef5196fSTobias Grosser     return Names;
452aef5196fSTobias Grosser   }
453aef5196fSTobias Grosser 
454e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
455e938517eSTobias Grosser   ///
456f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
457f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
458f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
459f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
460e938517eSTobias Grosser   ///
461e938517eSTobias Grosser   /// @returns A new ppcg scop.
462e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
463e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
464e938517eSTobias Grosser 
465e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
466e938517eSTobias Grosser 
467e938517eSTobias Grosser     PPCGScop->start = 0;
468e938517eSTobias Grosser     PPCGScop->end = 0;
469e938517eSTobias Grosser 
470f384594dSTobias Grosser     PPCGScop->context = S->getContext();
471f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
472e938517eSTobias Grosser     PPCGScop->call = nullptr;
473f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
474f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
475e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
476f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
477f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
478f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
479f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
480e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
481f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
482e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
483e938517eSTobias Grosser 
484e938517eSTobias Grosser     PPCGScop->independence = nullptr;
485e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
486e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
487e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
488e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
489e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
490e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
491e938517eSTobias Grosser 
492f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
493aef5196fSTobias Grosser     PPCGScop->names = getNames();
494e938517eSTobias Grosser 
495e938517eSTobias Grosser     PPCGScop->pet = nullptr;
496e938517eSTobias Grosser 
497f384594dSTobias Grosser     compute_tagger(PPCGScop);
498f384594dSTobias Grosser     compute_dependences(PPCGScop);
499f384594dSTobias Grosser 
500e938517eSTobias Grosser     return PPCGScop;
501e938517eSTobias Grosser   }
502e938517eSTobias Grosser 
50360f63b49STobias Grosser   /// Collect the array acesses in a statement.
50460f63b49STobias Grosser   ///
50560f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
50660f63b49STobias Grosser   ///
50760f63b49STobias Grosser   /// @returns A list of array accesses.
50860f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
50960f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
51060f63b49STobias Grosser 
51160f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
51260f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
51360f63b49STobias Grosser       Access->read = Acc->isRead();
51460f63b49STobias Grosser       Access->write = Acc->isWrite();
51560f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
51660f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
51760f63b49STobias Grosser       Space = isl_space_range(Space);
51860f63b49STobias Grosser       Space = isl_space_from_range(Space);
5196293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
52060f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
52160f63b49STobias Grosser       Access->tagged_access =
52260f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
52360f63b49STobias Grosser       Access->exact_write = Acc->isWrite();
52460f63b49STobias Grosser       Access->ref_id = Acc->getId();
52560f63b49STobias Grosser       Access->next = Accesses;
52660f63b49STobias Grosser       Accesses = Access;
52760f63b49STobias Grosser     }
52860f63b49STobias Grosser 
52960f63b49STobias Grosser     return Accesses;
53060f63b49STobias Grosser   }
53160f63b49STobias Grosser 
53269b46751STobias Grosser   /// Collect the list of GPU statements.
53369b46751STobias Grosser   ///
53469b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
53569b46751STobias Grosser   /// as well as a list with all memory accesses.
53669b46751STobias Grosser   ///
53769b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
53869b46751STobias Grosser   ///
53969b46751STobias Grosser   /// @returns A linked-list of statements.
54069b46751STobias Grosser   gpu_stmt *getStatements() {
54169b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
54269b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
54369b46751STobias Grosser 
54469b46751STobias Grosser     int i = 0;
54569b46751STobias Grosser     for (auto &Stmt : *S) {
54669b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
54769b46751STobias Grosser 
54869b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
54969b46751STobias Grosser 
55069b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
55169b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
55260f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
55369b46751STobias Grosser       i++;
55469b46751STobias Grosser     }
55569b46751STobias Grosser 
55669b46751STobias Grosser     return Stmts;
55769b46751STobias Grosser   }
55869b46751STobias Grosser 
55960f63b49STobias Grosser   /// Derive the extent of an array.
56060f63b49STobias Grosser   ///
56160f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
56260f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
56360f63b49STobias Grosser   ///
56460f63b49STobias Grosser   /// @param Array The array to derive the extent for.
56560f63b49STobias Grosser   ///
56660f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
56760f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
56860f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
56960f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
57060f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
57160f63b49STobias Grosser     isl_set *AccessSet =
57260f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
57360f63b49STobias Grosser     isl_union_set_free(AccessUSet);
57460f63b49STobias Grosser 
57560f63b49STobias Grosser     return AccessSet;
57660f63b49STobias Grosser   }
57760f63b49STobias Grosser 
57860f63b49STobias Grosser   /// Derive the bounds of an array.
57960f63b49STobias Grosser   ///
58060f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
58160f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
58260f63b49STobias Grosser   /// ScopArrayInfo.
58360f63b49STobias Grosser   ///
58460f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
58560f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
58660f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
58760f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
58860f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
58960f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
59060f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
59160f63b49STobias Grosser       isl_set_free(Dom);
59260f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
59360f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
59460f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
59560f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
59660f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
59760f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
59860f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
59960f63b49STobias Grosser     }
60060f63b49STobias Grosser 
60160f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
60260f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
60360f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
60460f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
60560f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
60660f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
60760f63b49STobias Grosser     }
60860f63b49STobias Grosser   }
60960f63b49STobias Grosser 
61060f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
61160f63b49STobias Grosser   ///
61260f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
61360f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
61460f63b49STobias Grosser     int i = 0;
61560f63b49STobias Grosser     for (auto &Element : S->arrays()) {
61660f63b49STobias Grosser       ScopArrayInfo *Array = Element.second.get();
61760f63b49STobias Grosser 
61860f63b49STobias Grosser       std::string TypeName;
61960f63b49STobias Grosser       raw_string_ostream OS(TypeName);
62060f63b49STobias Grosser 
62160f63b49STobias Grosser       OS << *Array->getElementType();
62260f63b49STobias Grosser       TypeName = OS.str();
62360f63b49STobias Grosser 
62460f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
62560f63b49STobias Grosser 
62660f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
62760f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
62860f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
62960f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
63060f63b49STobias Grosser       PPCGArray.extent = nullptr;
63160f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
63260f63b49STobias Grosser       PPCGArray.bound =
63360f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
63460f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
63560f63b49STobias Grosser       PPCGArray.n_ref = 0;
63660f63b49STobias Grosser       PPCGArray.refs = nullptr;
63760f63b49STobias Grosser       PPCGArray.accessed = true;
63860f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
63960f63b49STobias Grosser       PPCGArray.has_compound_element = false;
64060f63b49STobias Grosser       PPCGArray.local = false;
64160f63b49STobias Grosser       PPCGArray.declare_local = false;
64260f63b49STobias Grosser       PPCGArray.global = false;
64360f63b49STobias Grosser       PPCGArray.linearize = false;
64460f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
64560f63b49STobias Grosser 
64660f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
6472d010dafSTobias Grosser       i++;
648b9fc860aSTobias Grosser 
649b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
65060f63b49STobias Grosser     }
65160f63b49STobias Grosser   }
65260f63b49STobias Grosser 
65360f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
65460f63b49STobias Grosser   ///
65560f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
65660f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
65760f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
65860f63b49STobias Grosser 
65960f63b49STobias Grosser     for (auto &Item : S->arrays()) {
66060f63b49STobias Grosser       ScopArrayInfo *Array = Item.second.get();
66160f63b49STobias Grosser       isl_space *Space = Array->getSpace();
66260f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
66360f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
66460f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
66560f63b49STobias Grosser     }
66660f63b49STobias Grosser 
66760f63b49STobias Grosser     return Maps;
66860f63b49STobias Grosser   }
66960f63b49STobias Grosser 
670e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
671e938517eSTobias Grosser   ///
672e938517eSTobias Grosser   /// @returns A new gpu grogram description.
673e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
674e938517eSTobias Grosser 
675e938517eSTobias Grosser     if (!PPCGScop)
676e938517eSTobias Grosser       return nullptr;
677e938517eSTobias Grosser 
678e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
679e938517eSTobias Grosser 
680e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
681e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
682aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
68360f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
68460f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
68560f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
68660f63b49STobias Grosser     PPCGProg->tagged_must_kill =
68760f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
68860f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
68960f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
69060f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
691e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
692e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
69369b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
69469b46751STobias Grosser     PPCGProg->stmts = getStatements();
69560f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
69660f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
69760f63b49STobias Grosser                                        PPCGProg->n_array);
69860f63b49STobias Grosser 
69960f63b49STobias Grosser     createArrays(PPCGProg);
700e938517eSTobias Grosser 
701e938517eSTobias Grosser     return PPCGProg;
702e938517eSTobias Grosser   }
703e938517eSTobias Grosser 
70469b46751STobias Grosser   struct PrintGPUUserData {
70569b46751STobias Grosser     struct cuda_info *CudaInfo;
70669b46751STobias Grosser     struct gpu_prog *PPCGProg;
70769b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
70869b46751STobias Grosser   };
70969b46751STobias Grosser 
71069b46751STobias Grosser   /// Print a user statement node in the host code.
71169b46751STobias Grosser   ///
71269b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
71369b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
71469b46751STobias Grosser   /// host ast.
71569b46751STobias Grosser   ///
71669b46751STobias Grosser   /// @param P The printer to print to
71769b46751STobias Grosser   /// @param Options The printing options to use
71869b46751STobias Grosser   /// @param Node The node to print
71969b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
72069b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
72169b46751STobias Grosser   ///
72269b46751STobias Grosser   /// @returns A printer to which the output has been printed.
72369b46751STobias Grosser   static __isl_give isl_printer *
72469b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
72569b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
72669b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
72769b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
72869b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
72969b46751STobias Grosser 
73069b46751STobias Grosser     if (Id) {
73120251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
73220251734STobias Grosser 
73320251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
73420251734STobias Grosser       // otherwise try to call pet functionality that is not available in
73520251734STobias Grosser       // Polly.
73620251734STobias Grosser       if (IsUser) {
73720251734STobias Grosser         P = isl_printer_start_line(P);
73820251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
73920251734STobias Grosser         P = isl_printer_end_line(P);
74020251734STobias Grosser         isl_id_free(Id);
74120251734STobias Grosser         isl_ast_print_options_free(Options);
74220251734STobias Grosser         return P;
74320251734STobias Grosser       }
74420251734STobias Grosser 
74569b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
74669b46751STobias Grosser       isl_id_free(Id);
74769b46751STobias Grosser       Data->Kernels.push_back(Kernel);
74869b46751STobias Grosser     }
74969b46751STobias Grosser 
75069b46751STobias Grosser     return print_host_user(P, Options, Node, User);
75169b46751STobias Grosser   }
75269b46751STobias Grosser 
75369b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
75469b46751STobias Grosser   ///
75569b46751STobias Grosser   /// @param Kernel The kernel to print
75669b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
75769b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
75869b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
75969b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
76069b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
76169b46751STobias Grosser     char *String = isl_printer_get_str(P);
76269b46751STobias Grosser     printf("%s\n", String);
76369b46751STobias Grosser     free(String);
76469b46751STobias Grosser     isl_printer_free(P);
76569b46751STobias Grosser   }
76669b46751STobias Grosser 
76769b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
76869b46751STobias Grosser   ///
76969b46751STobias Grosser   /// @param Tree An AST describing GPU code
77069b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
77169b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
77269b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
77369b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
77469b46751STobias Grosser 
77569b46751STobias Grosser     PrintGPUUserData Data;
77669b46751STobias Grosser     Data.PPCGProg = PPCGProg;
77769b46751STobias Grosser 
77869b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
77969b46751STobias Grosser     Options =
78069b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
78169b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
78269b46751STobias Grosser     char *String = isl_printer_get_str(P);
78369b46751STobias Grosser     printf("# host\n");
78469b46751STobias Grosser     printf("%s\n", String);
78569b46751STobias Grosser     free(String);
78669b46751STobias Grosser     isl_printer_free(P);
78769b46751STobias Grosser 
78869b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
78969b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
79069b46751STobias Grosser       printKernel(Kernel);
79169b46751STobias Grosser     }
79269b46751STobias Grosser   }
79369b46751STobias Grosser 
794f384594dSTobias Grosser   // Generate a GPU program using PPCG.
795f384594dSTobias Grosser   //
796f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
797f384594dSTobias Grosser   //
798f384594dSTobias Grosser   //  1) Compute new schedule for the program.
799f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
800f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
801f384594dSTobias Grosser   //
802f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
803f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
804f384594dSTobias Grosser   // strategy directly from this pass.
805f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
806f384594dSTobias Grosser 
807f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
808f384594dSTobias Grosser 
809f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
810f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
811f384594dSTobias Grosser     PPCGGen->print = nullptr;
812f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
81360c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
814f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
815f384594dSTobias Grosser     PPCGGen->tree = nullptr;
816f384594dSTobias Grosser     PPCGGen->types.n = 0;
817f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
818f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
819f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
820f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
821f384594dSTobias Grosser 
822f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
823f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
824f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
8252341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
826f384594dSTobias Grosser 
827f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
828f384594dSTobias Grosser 
829aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
830aef5196fSTobias Grosser 
83169b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
832aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
83369b46751STobias Grosser     } else {
834aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
83569b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
83669b46751STobias Grosser     }
837aef5196fSTobias Grosser 
838f384594dSTobias Grosser     if (DumpSchedule) {
839f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
840f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
841f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
842f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
843f384594dSTobias Grosser       if (Schedule)
844f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
845f384594dSTobias Grosser       else
846f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
847f384594dSTobias Grosser 
848f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
849f384594dSTobias Grosser       isl_printer_free(P);
850f384594dSTobias Grosser     }
851f384594dSTobias Grosser 
85269b46751STobias Grosser     if (DumpCode) {
85369b46751STobias Grosser       printf("Code\n");
85469b46751STobias Grosser       printf("====\n");
85569b46751STobias Grosser       if (PPCGGen->tree)
85669b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
85769b46751STobias Grosser       else
85869b46751STobias Grosser         printf("No code generated\n");
85969b46751STobias Grosser     }
86069b46751STobias Grosser 
861f384594dSTobias Grosser     isl_schedule_free(Schedule);
862f384594dSTobias Grosser 
863f384594dSTobias Grosser     return PPCGGen;
864f384594dSTobias Grosser   }
865f384594dSTobias Grosser 
866f384594dSTobias Grosser   /// Free gpu_gen structure.
867f384594dSTobias Grosser   ///
868f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
869f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
870f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
871f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
872f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
873f384594dSTobias Grosser     free(PPCGGen);
874f384594dSTobias Grosser   }
875f384594dSTobias Grosser 
876b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
877b307ed4dSTobias Grosser   ///
878b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
879b307ed4dSTobias Grosser   /// ourselves.
880b307ed4dSTobias Grosser   ///
881b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
882b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
883b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
884b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
885b307ed4dSTobias Grosser     free(PPCGScop->options);
886b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
887b307ed4dSTobias Grosser   }
888b307ed4dSTobias Grosser 
88938fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
89038fc0aedSTobias Grosser   ///
89132837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
89232837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
89332837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
89438fc0aedSTobias Grosser     ScopAnnotator Annotator;
89538fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
89638fc0aedSTobias Grosser 
89738fc0aedSTobias Grosser     Region *R = &S->getRegion();
89838fc0aedSTobias Grosser 
89938fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
90038fc0aedSTobias Grosser 
90138fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
90238fc0aedSTobias Grosser 
90338fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
90438fc0aedSTobias Grosser 
90532837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
90632837fe3STobias Grosser                                Prog);
90738fc0aedSTobias Grosser 
90838fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
90938fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
91038fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
91138fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
91238fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
91338fc0aedSTobias Grosser     // code generating this scop.
91438fc0aedSTobias Grosser     BasicBlock *StartBlock =
91538fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
91638fc0aedSTobias Grosser 
91738fc0aedSTobias Grosser     // TODO: Handle LICM
91838fc0aedSTobias Grosser     // TODO: Verify run-time checks
91938fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
92038fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
92138fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
92238fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
92338fc0aedSTobias Grosser     NodeBuilder.create(Root);
92438fc0aedSTobias Grosser     NodeBuilder.finalizeSCoP(*S);
92538fc0aedSTobias Grosser   }
92638fc0aedSTobias Grosser 
927e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
928e938517eSTobias Grosser     S = &CurrentScop;
92938fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
93038fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
93138fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
93238fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
93338fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
934e938517eSTobias Grosser 
935e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
936e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
937f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
93838fc0aedSTobias Grosser 
93938fc0aedSTobias Grosser     if (PPCGGen->tree)
94032837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
94138fc0aedSTobias Grosser 
942b307ed4dSTobias Grosser     freeOptions(PPCGScop);
943f384594dSTobias Grosser     freePPCGGen(PPCGGen);
944e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
945e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
946e938517eSTobias Grosser 
947e938517eSTobias Grosser     return true;
948e938517eSTobias Grosser   }
9499dfe4e7cSTobias Grosser 
9509dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
9519dfe4e7cSTobias Grosser 
9529dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
9539dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
9549dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
9559dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
9569dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
9579dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
9589dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
9599dfe4e7cSTobias Grosser 
9609dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
9619dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
9629dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
9639dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
9649dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
9659dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
9669dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
9679dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
9689dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
9699dfe4e7cSTobias Grosser 
9709dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
9719dfe4e7cSTobias Grosser     //        region tree.
9729dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
9739dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
9749dfe4e7cSTobias Grosser   }
9759dfe4e7cSTobias Grosser };
9769dfe4e7cSTobias Grosser }
9779dfe4e7cSTobias Grosser 
9789dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
9799dfe4e7cSTobias Grosser 
9809dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
9819dfe4e7cSTobias Grosser 
9829dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
9839dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
9849dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
9859dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
9869dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
9879dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
9889dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
9899dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
9909dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
9919dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
992