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" 21edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 22*74dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 239dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 249dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 259dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 28*74dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 29*74dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 30*74dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 31*74dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 32*74dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 33*74dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 349dfe4e7cSTobias Grosser 35f384594dSTobias Grosser #include "isl/union_map.h" 36f384594dSTobias Grosser 37e938517eSTobias Grosser extern "C" { 38a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 39a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 40a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 41a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 42a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 43e938517eSTobias Grosser } 44e938517eSTobias Grosser 459dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 469dfe4e7cSTobias Grosser 479dfe4e7cSTobias Grosser using namespace polly; 489dfe4e7cSTobias Grosser using namespace llvm; 499dfe4e7cSTobias Grosser 509dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 519dfe4e7cSTobias Grosser 52f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 53f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 54681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 55f384594dSTobias Grosser cl::cat(PollyCategory)); 5669b46751STobias Grosser 5769b46751STobias Grosser static cl::opt<bool> 5869b46751STobias Grosser DumpCode("polly-acc-dump-code", 5969b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6069b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6169b46751STobias Grosser 6232837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6332837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6432837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 6532837fe3STobias Grosser cl::cat(PollyCategory)); 6632837fe3STobias Grosser 67*74dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 68*74dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 69*74dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 70*74dc3cb4STobias Grosser cl::cat(PollyCategory)); 71*74dc3cb4STobias Grosser 72*74dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 73*74dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 74*74dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 75*74dc3cb4STobias Grosser cl::cat(PollyCategory)); 76*74dc3cb4STobias Grosser 77*74dc3cb4STobias Grosser static cl::opt<std::string> 78*74dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 79*74dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 80*74dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 81*74dc3cb4STobias Grosser 8260c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 8360c60025STobias Grosser /// 8460c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 8560c60025STobias Grosser /// of the scheduled ScopStmts. 8660c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 87edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 8860c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 8960c60025STobias Grosser isl_id *Id, void *User), 9060c60025STobias Grosser void *UserIndex, 9160c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 92edb885cbSTobias Grosser void *UserExpr) { 9360c60025STobias Grosser 94edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 9560c60025STobias Grosser 96edb885cbSTobias Grosser isl_ctx *Ctx; 97edb885cbSTobias Grosser 98edb885cbSTobias Grosser if (!Stmt || !Build) 99edb885cbSTobias Grosser return NULL; 100edb885cbSTobias Grosser 101edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 102edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 103edb885cbSTobias Grosser 104edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 105edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 106edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 107edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 108edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 109edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 110edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 111edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 112edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 113edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 114edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 115edb885cbSTobias Grosser } 116edb885cbSTobias Grosser 117edb885cbSTobias Grosser return RefToExpr; 11860c60025STobias Grosser } 119f384594dSTobias Grosser 12038fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 12138fc0aedSTobias Grosser /// 12238fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 12338fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality 12438fc0aedSTobias Grosser /// for generating GPU specific user nodes. 12538fc0aedSTobias Grosser /// 12638fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 12738fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 12838fc0aedSTobias Grosser public: 12938fc0aedSTobias Grosser GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P, 13038fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 13132837fe3STobias Grosser DominatorTree &DT, Scop &S, gpu_prog *Prog) 132edb885cbSTobias Grosser : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) { 133edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 134edb885cbSTobias Grosser } 13538fc0aedSTobias Grosser 13638fc0aedSTobias Grosser private: 137*74dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 138*74dc3cb4STobias Grosser /// 139*74dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 140*74dc3cb4STobias Grosser /// more. 141*74dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 142*74dc3cb4STobias Grosser 14332837fe3STobias Grosser /// A module containing GPU code. 14432837fe3STobias Grosser /// 14532837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 14632837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 14732837fe3STobias Grosser 14832837fe3STobias Grosser /// The GPU program we generate code for. 14932837fe3STobias Grosser gpu_prog *Prog; 15032837fe3STobias Grosser 151472f9654STobias Grosser /// Class to free isl_ids. 152472f9654STobias Grosser class IslIdDeleter { 153472f9654STobias Grosser public: 154472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 155472f9654STobias Grosser }; 156472f9654STobias Grosser 157472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 158472f9654STobias Grosser /// 159472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 160472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 161472f9654STobias Grosser 162edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 163edb885cbSTobias Grosser 16438fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 16538fc0aedSTobias Grosser /// 16638fc0aedSTobias Grosser /// These AST nodes can be of type: 16738fc0aedSTobias Grosser /// 16838fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 16938fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 17038fc0aedSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer (TODO) 1715260c041STobias Grosser /// - In-kernel synchronization 1725260c041STobias Grosser /// - In-kernel memory copy statement 17338fc0aedSTobias Grosser /// 1741fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 1751fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 17632837fe3STobias Grosser 177edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 178edb885cbSTobias Grosser /// 179edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 180edb885cbSTobias Grosser /// 181edb885cbSTobias Grosser /// @returns A set of values referenced by the kernel. 182edb885cbSTobias Grosser SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel); 183edb885cbSTobias Grosser 18432837fe3STobias Grosser /// Create GPU kernel. 18532837fe3STobias Grosser /// 18632837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 18732837fe3STobias Grosser /// 18832837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 18932837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 19032837fe3STobias Grosser 19132837fe3STobias Grosser /// Create kernel function. 19232837fe3STobias Grosser /// 19332837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 19432837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 19532837fe3STobias Grosser /// start block of this newly created function. 19632837fe3STobias Grosser /// 19732837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 198edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 199edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 200edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 20132837fe3STobias Grosser 20232837fe3STobias Grosser /// Create the declaration of a kernel function. 20332837fe3STobias Grosser /// 20432837fe3STobias Grosser /// The kernel function takes as arguments: 20532837fe3STobias Grosser /// 20632837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 207f6044bd0STobias Grosser /// - Host iterators 208c84a1995STobias Grosser /// - Parameters 20932837fe3STobias Grosser /// - Other LLVM Value references (TODO) 21032837fe3STobias Grosser /// 21132837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 212edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 213edb885cbSTobias Grosser /// 21432837fe3STobias Grosser /// @returns The newly declared function. 215edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 216edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 21732837fe3STobias Grosser 218472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 219472f9654STobias Grosser /// 220472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 221472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 222472f9654STobias Grosser 223edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 224edb885cbSTobias Grosser /// 225edb885cbSTobias Grosser /// @param Expr The expression containing the call. 226edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 227edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 228edb885cbSTobias Grosser 2295260c041STobias Grosser /// Create an in-kernel synchronization call. 2305260c041STobias Grosser void createKernelSync(); 2315260c041STobias Grosser 232*74dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 233*74dc3cb4STobias Grosser /// 234*74dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 235*74dc3cb4STobias Grosser std::string createKernelASM(); 236*74dc3cb4STobias Grosser 237*74dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 238*74dc3cb4STobias Grosser /// 239*74dc3cb4STobias Grosser /// @param F The function to remove references to. 240*74dc3cb4STobias Grosser void clearDominators(Function *F); 241*74dc3cb4STobias Grosser 242*74dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 243*74dc3cb4STobias Grosser /// 244*74dc3cb4STobias Grosser /// @param F The function to remove references to. 245*74dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 246*74dc3cb4STobias Grosser 247*74dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 248*74dc3cb4STobias Grosser /// 249*74dc3cb4STobias Grosser /// @param F The function to remove references to. 250*74dc3cb4STobias Grosser void clearLoops(Function *F); 251*74dc3cb4STobias Grosser 25232837fe3STobias Grosser /// Finalize the generation of the kernel function. 25332837fe3STobias Grosser /// 25432837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 25532837fe3STobias Grosser /// dump its IR to stderr. 25632837fe3STobias Grosser void finalizeKernelFunction(); 2571fb9b64dSTobias Grosser }; 2581fb9b64dSTobias Grosser 2595260c041STobias Grosser /// Check if one string is a prefix of another. 2605260c041STobias Grosser /// 2615260c041STobias Grosser /// @param String The string in which to look for the prefix. 2625260c041STobias Grosser /// @param Prefix The prefix to look for. 2635260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 2645260c041STobias Grosser return String.find(Prefix) == 0; 2655260c041STobias Grosser } 2665260c041STobias Grosser 2671fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 26832837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 26932837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 27032837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 27132837fe3STobias Grosser isl_id_free(Id); 27232837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 27332837fe3STobias Grosser 27432837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 27532837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 27632837fe3STobias Grosser createKernel(UserStmt); 27732837fe3STobias Grosser isl_ast_expr_free(Expr); 27832837fe3STobias Grosser return; 27932837fe3STobias Grosser } 28032837fe3STobias Grosser 2815260c041STobias Grosser if (isPrefix(Str, "to_device") || isPrefix(Str, "from_device")) { 2825260c041STobias Grosser // TODO: Insert memory copies 28332837fe3STobias Grosser isl_ast_expr_free(Expr); 2841fb9b64dSTobias Grosser isl_ast_node_free(UserStmt); 28538fc0aedSTobias Grosser return; 28638fc0aedSTobias Grosser } 28738fc0aedSTobias Grosser 2885260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 2895260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 2905260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 2915260c041STobias Grosser isl_id_free(Anno); 2925260c041STobias Grosser 2935260c041STobias Grosser switch (KernelStmt->type) { 2945260c041STobias Grosser case ppcg_kernel_domain: 295edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 2965260c041STobias Grosser isl_ast_node_free(UserStmt); 2975260c041STobias Grosser return; 2985260c041STobias Grosser case ppcg_kernel_copy: 2995260c041STobias Grosser // TODO: Create kernel copy stmt 3005260c041STobias Grosser isl_ast_expr_free(Expr); 3015260c041STobias Grosser isl_ast_node_free(UserStmt); 3025260c041STobias Grosser return; 3035260c041STobias Grosser case ppcg_kernel_sync: 3045260c041STobias Grosser createKernelSync(); 3055260c041STobias Grosser isl_ast_expr_free(Expr); 3065260c041STobias Grosser isl_ast_node_free(UserStmt); 3075260c041STobias Grosser return; 3085260c041STobias Grosser } 3095260c041STobias Grosser 3105260c041STobias Grosser isl_ast_expr_free(Expr); 3115260c041STobias Grosser isl_ast_node_free(UserStmt); 3125260c041STobias Grosser return; 3135260c041STobias Grosser } 3145260c041STobias Grosser 315edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 316edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 317edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 318edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 319edb885cbSTobias Grosser 320edb885cbSTobias Grosser LoopToScevMapT LTS; 321edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 322edb885cbSTobias Grosser 323edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 324edb885cbSTobias Grosser 325edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 326edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 327edb885cbSTobias Grosser else 328edb885cbSTobias Grosser assert(0 && "Region statement not supported\n"); 329edb885cbSTobias Grosser } 330edb885cbSTobias Grosser 3315260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 3325260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 3335260c041STobias Grosser auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 3345260c041STobias Grosser Builder.CreateCall(Sync, {}); 3355260c041STobias Grosser } 3365260c041STobias Grosser 337edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 338edb885cbSTobias Grosser /// 339edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 340edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 341edb885cbSTobias Grosser /// 342edb885cbSTobias Grosser /// @param Node The node to collect references for. 343edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 344edb885cbSTobias Grosser /// 345edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 346edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 347edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 348edb885cbSTobias Grosser return isl_bool_true; 349edb885cbSTobias Grosser 350edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 351edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 352edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 353edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 354edb885cbSTobias Grosser isl_id_free(Id); 355edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 356edb885cbSTobias Grosser isl_ast_expr_free(Expr); 357edb885cbSTobias Grosser 358edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 359edb885cbSTobias Grosser return isl_bool_true; 360edb885cbSTobias Grosser 361edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 362edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 363edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 364edb885cbSTobias Grosser isl_id_free(Id); 365edb885cbSTobias Grosser 366edb885cbSTobias Grosser addReferencesFromStmt(Stmt, User); 367edb885cbSTobias Grosser 368edb885cbSTobias Grosser return isl_bool_true; 369edb885cbSTobias Grosser } 370edb885cbSTobias Grosser 371edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 372edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 373edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 374edb885cbSTobias Grosser SetVector<const Loop *> Loops; 375edb885cbSTobias Grosser SubtreeReferences References = { 376edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 377edb885cbSTobias Grosser 378edb885cbSTobias Grosser for (const auto &I : IDToValue) 379edb885cbSTobias Grosser SubtreeValues.insert(I.second); 380edb885cbSTobias Grosser 381edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 382edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 383edb885cbSTobias Grosser 384edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 385edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 386edb885cbSTobias Grosser 387edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 388edb885cbSTobias Grosser SubtreeValues.remove(SAI.second->getBasePtr()); 389edb885cbSTobias Grosser 390edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 391edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 392edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 393edb885cbSTobias Grosser assert(IDToValue.count(Id)); 394edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 395edb885cbSTobias Grosser SubtreeValues.remove(Val); 396edb885cbSTobias Grosser isl_id_free(Id); 397edb885cbSTobias Grosser } 398edb885cbSTobias Grosser isl_space_free(Space); 399edb885cbSTobias Grosser 400edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 401edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 402edb885cbSTobias Grosser assert(IDToValue.count(Id)); 403edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 404edb885cbSTobias Grosser SubtreeValues.remove(Val); 405edb885cbSTobias Grosser isl_id_free(Id); 406edb885cbSTobias Grosser } 407edb885cbSTobias Grosser 408edb885cbSTobias Grosser return SubtreeValues; 409edb885cbSTobias Grosser } 410edb885cbSTobias Grosser 411*74dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 412*74dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 413*74dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 414*74dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 415*74dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 416*74dc3cb4STobias Grosser 417*74dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 418*74dc3cb4STobias Grosser DT.eraseNode(BB); 419*74dc3cb4STobias Grosser } 420*74dc3cb4STobias Grosser 421*74dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 422*74dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 423*74dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 424*74dc3cb4STobias Grosser if (L) 425*74dc3cb4STobias Grosser SE.forgetLoop(L); 426*74dc3cb4STobias Grosser } 427*74dc3cb4STobias Grosser } 428*74dc3cb4STobias Grosser 429*74dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 430*74dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 431*74dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 432*74dc3cb4STobias Grosser if (L) 433*74dc3cb4STobias Grosser SE.forgetLoop(L); 434*74dc3cb4STobias Grosser LI.removeBlock(&BB); 435*74dc3cb4STobias Grosser } 436*74dc3cb4STobias Grosser } 437*74dc3cb4STobias Grosser 43832837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 43932837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 44032837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 44132837fe3STobias Grosser isl_id_free(Id); 44232837fe3STobias Grosser isl_ast_node_free(KernelStmt); 44332837fe3STobias Grosser 444edb885cbSTobias Grosser SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel); 445edb885cbSTobias Grosser 44632837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 44732837fe3STobias Grosser 44832837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 449472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 450edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 45132837fe3STobias Grosser 452edb885cbSTobias Grosser SetVector<const Loop *> Loops; 453edb885cbSTobias Grosser 454edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 455edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 456edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 457edb885cbSTobias Grosser for (const Loop *L : Loops) { 458edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 459edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 460edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 461edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 462edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 463edb885cbSTobias Grosser SubtreeValues.insert(V); 464edb885cbSTobias Grosser } 465edb885cbSTobias Grosser 466edb885cbSTobias Grosser createKernelFunction(Kernel, SubtreeValues); 46732837fe3STobias Grosser 46859ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 46959ab0705STobias Grosser 470*74dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 471*74dc3cb4STobias Grosser clearDominators(F); 472*74dc3cb4STobias Grosser clearScalarEvolution(F); 473*74dc3cb4STobias Grosser clearLoops(F); 474*74dc3cb4STobias Grosser 47532837fe3STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 476472f9654STobias Grosser IDToValue = HostIDs; 47732837fe3STobias Grosser 478edb885cbSTobias Grosser ValueMap = HostValueMap; 479edb885cbSTobias Grosser ScalarMap.clear(); 480edb885cbSTobias Grosser PHIOpMap.clear(); 481edb885cbSTobias Grosser EscapeMap.clear(); 482edb885cbSTobias Grosser IDToSAI.clear(); 483*74dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 484*74dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 485*74dc3cb4STobias Grosser S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array); 486*74dc3cb4STobias Grosser LocalArrays.clear(); 487edb885cbSTobias Grosser 48832837fe3STobias Grosser finalizeKernelFunction(); 48932837fe3STobias Grosser } 49032837fe3STobias Grosser 49132837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 49232837fe3STobias Grosser /// 49332837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 49432837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 49532837fe3STobias Grosser std::string Ret = "e"; 49632837fe3STobias Grosser 49732837fe3STobias Grosser if (!is64Bit) 49832837fe3STobias Grosser Ret += "-p:32:32"; 49932837fe3STobias Grosser 50032837fe3STobias Grosser Ret += "-i64:64-v16:16-v32:32-n16:32:64"; 50132837fe3STobias Grosser 50232837fe3STobias Grosser return Ret; 50332837fe3STobias Grosser } 50432837fe3STobias Grosser 505edb885cbSTobias Grosser Function * 506edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 507edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 50832837fe3STobias Grosser std::vector<Type *> Args; 50932837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 51032837fe3STobias Grosser 51132837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 51232837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 51332837fe3STobias Grosser continue; 51432837fe3STobias Grosser 51532837fe3STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 51632837fe3STobias Grosser } 51732837fe3STobias Grosser 518f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 519f6044bd0STobias Grosser 520f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 521f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 522f6044bd0STobias Grosser 523c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 524c84a1995STobias Grosser 525c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) 526c84a1995STobias Grosser Args.push_back(Builder.getInt64Ty()); 527c84a1995STobias Grosser 528edb885cbSTobias Grosser for (auto *V : SubtreeValues) 529edb885cbSTobias Grosser Args.push_back(V->getType()); 530edb885cbSTobias Grosser 53132837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 53232837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 53332837fe3STobias Grosser GPUModule.get()); 53432837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 53532837fe3STobias Grosser 53632837fe3STobias Grosser auto Arg = FN->arg_begin(); 53732837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 53832837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 53932837fe3STobias Grosser continue; 54032837fe3STobias Grosser 541edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 542edb885cbSTobias Grosser 543edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 544edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 545edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 546edb885cbSTobias Grosser Value *Val = &*Arg; 547edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 548edb885cbSTobias Grosser isl_ast_build *Build = 549edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 550edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 551edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 552edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 553edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 554edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 555edb885cbSTobias Grosser } 556edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 557edb885cbSTobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array); 558*74dc3cb4STobias Grosser LocalArrays.push_back(Val); 559edb885cbSTobias Grosser 560edb885cbSTobias Grosser isl_ast_build_free(Build); 561edb885cbSTobias Grosser isl_id_free(Id); 562edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 56332837fe3STobias Grosser Arg++; 56432837fe3STobias Grosser } 56532837fe3STobias Grosser 566f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 567f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 568f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 569f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 570f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 571f6044bd0STobias Grosser Arg++; 572f6044bd0STobias Grosser } 573f6044bd0STobias Grosser 574c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 575c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 576c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 577c84a1995STobias Grosser IDToValue[Id] = &*Arg; 578c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 579c84a1995STobias Grosser Arg++; 580c84a1995STobias Grosser } 581c84a1995STobias Grosser 582edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 583edb885cbSTobias Grosser Arg->setName(V->getName()); 584edb885cbSTobias Grosser ValueMap[V] = &*Arg; 585edb885cbSTobias Grosser Arg++; 586edb885cbSTobias Grosser } 587edb885cbSTobias Grosser 58832837fe3STobias Grosser return FN; 58932837fe3STobias Grosser } 59032837fe3STobias Grosser 591472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 592472f9654STobias Grosser Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x, 593472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_ctaid_y}; 594472f9654STobias Grosser 595472f9654STobias Grosser Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x, 596472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_tid_y, 597472f9654STobias Grosser Intrinsic::nvvm_read_ptx_sreg_tid_z}; 598472f9654STobias Grosser 599472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 600472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 601472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 602472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 603472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 604472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 605472f9654STobias Grosser IDToValue[Id] = Val; 606472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 607472f9654STobias Grosser }; 608472f9654STobias Grosser 609472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 610472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 611472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 612472f9654STobias Grosser } 613472f9654STobias Grosser 614472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 615472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 616472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 617472f9654STobias Grosser } 618472f9654STobias Grosser } 619472f9654STobias Grosser 620edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel, 621edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 62232837fe3STobias Grosser 62332837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 62432837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 62532837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 62632837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 62732837fe3STobias Grosser 628edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 62932837fe3STobias Grosser 63059ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 63132837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 63232837fe3STobias Grosser 63359ab0705STobias Grosser DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 63459ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 63559ab0705STobias Grosser 63632837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 63732837fe3STobias Grosser Builder.CreateRetVoid(); 63832837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 639472f9654STobias Grosser 640472f9654STobias Grosser insertKernelIntrinsics(Kernel); 64132837fe3STobias Grosser } 64232837fe3STobias Grosser 643*74dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 644*74dc3cb4STobias Grosser llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda")); 645*74dc3cb4STobias Grosser std::string ErrMsg; 646*74dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 647*74dc3cb4STobias Grosser 648*74dc3cb4STobias Grosser if (!GPUTarget) { 649*74dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 650*74dc3cb4STobias Grosser return ""; 651*74dc3cb4STobias Grosser } 652*74dc3cb4STobias Grosser 653*74dc3cb4STobias Grosser TargetOptions Options; 654*74dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 655*74dc3cb4STobias Grosser std::unique_ptr<TargetMachine> TargetM( 656*74dc3cb4STobias Grosser GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "", 657*74dc3cb4STobias Grosser Options, Optional<Reloc::Model>())); 658*74dc3cb4STobias Grosser 659*74dc3cb4STobias Grosser SmallString<0> ASMString; 660*74dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 661*74dc3cb4STobias Grosser llvm::legacy::PassManager PM; 662*74dc3cb4STobias Grosser 663*74dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 664*74dc3cb4STobias Grosser 665*74dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 666*74dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 667*74dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 668*74dc3cb4STobias Grosser return ""; 669*74dc3cb4STobias Grosser } 670*74dc3cb4STobias Grosser 671*74dc3cb4STobias Grosser PM.run(*GPUModule); 672*74dc3cb4STobias Grosser 673*74dc3cb4STobias Grosser return ASMStream.str(); 674*74dc3cb4STobias Grosser } 675*74dc3cb4STobias Grosser 67632837fe3STobias Grosser void GPUNodeBuilder::finalizeKernelFunction() { 67732837fe3STobias Grosser 67832837fe3STobias Grosser if (DumpKernelIR) 67932837fe3STobias Grosser outs() << *GPUModule << "\n"; 68032837fe3STobias Grosser 681*74dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 682*74dc3cb4STobias Grosser 683*74dc3cb4STobias Grosser if (DumpKernelASM) 684*74dc3cb4STobias Grosser outs() << Assembly << "\n"; 685*74dc3cb4STobias Grosser 68632837fe3STobias Grosser GPUModule.release(); 687472f9654STobias Grosser KernelIDs.clear(); 68832837fe3STobias Grosser } 68932837fe3STobias Grosser 6909dfe4e7cSTobias Grosser namespace { 6919dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 6929dfe4e7cSTobias Grosser public: 6939dfe4e7cSTobias Grosser static char ID; 6949dfe4e7cSTobias Grosser 695e938517eSTobias Grosser /// The scop that is currently processed. 696e938517eSTobias Grosser Scop *S; 697e938517eSTobias Grosser 69838fc0aedSTobias Grosser LoopInfo *LI; 69938fc0aedSTobias Grosser DominatorTree *DT; 70038fc0aedSTobias Grosser ScalarEvolution *SE; 70138fc0aedSTobias Grosser const DataLayout *DL; 70238fc0aedSTobias Grosser RegionInfo *RI; 70338fc0aedSTobias Grosser 7049dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 7059dfe4e7cSTobias Grosser 706e938517eSTobias Grosser /// Construct compilation options for PPCG. 707e938517eSTobias Grosser /// 708e938517eSTobias Grosser /// @returns The compilation options. 709e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 710e938517eSTobias Grosser auto DebugOptions = 711e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 712e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 713e938517eSTobias Grosser 714e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 715e938517eSTobias Grosser DebugOptions->dump_schedule = false; 716e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 717e938517eSTobias Grosser DebugOptions->dump_sizes = false; 718e938517eSTobias Grosser 719e938517eSTobias Grosser Options->debug = DebugOptions; 720e938517eSTobias Grosser 721e938517eSTobias Grosser Options->reschedule = true; 722e938517eSTobias Grosser Options->scale_tile_loops = false; 723e938517eSTobias Grosser Options->wrap = false; 724e938517eSTobias Grosser 725e938517eSTobias Grosser Options->non_negative_parameters = false; 726e938517eSTobias Grosser Options->ctx = nullptr; 727e938517eSTobias Grosser Options->sizes = nullptr; 728e938517eSTobias Grosser 7294eaedde5STobias Grosser Options->tile_size = 32; 7304eaedde5STobias Grosser 731e938517eSTobias Grosser Options->use_private_memory = false; 732e938517eSTobias Grosser Options->use_shared_memory = false; 733e938517eSTobias Grosser Options->max_shared_memory = 0; 734e938517eSTobias Grosser 735e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 736e938517eSTobias Grosser Options->openmp = false; 737e938517eSTobias Grosser Options->linearize_device_arrays = true; 738e938517eSTobias Grosser Options->live_range_reordering = false; 739e938517eSTobias Grosser 740e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 741e938517eSTobias Grosser Options->opencl_use_gpu = false; 742e938517eSTobias Grosser Options->opencl_n_include_file = 0; 743e938517eSTobias Grosser Options->opencl_include_files = nullptr; 744e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 745e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 746e938517eSTobias Grosser 747e938517eSTobias Grosser Options->save_schedule_file = nullptr; 748e938517eSTobias Grosser Options->load_schedule_file = nullptr; 749e938517eSTobias Grosser 750e938517eSTobias Grosser return Options; 751e938517eSTobias Grosser } 752e938517eSTobias Grosser 753f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 754f384594dSTobias Grosser /// 755f384594dSTobias Grosser /// Instead of a normal access of the form: 756f384594dSTobias Grosser /// 757f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 758f384594dSTobias Grosser /// 759f384594dSTobias Grosser /// a tagged access has the form 760f384594dSTobias Grosser /// 761f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 762f384594dSTobias Grosser /// 763f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 764f384594dSTobias Grosser /// triggered the access. 765f384594dSTobias Grosser /// 766f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 767f384594dSTobias Grosser /// 768f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 769f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 770f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 771f384594dSTobias Grosser 772f384594dSTobias Grosser for (auto &Stmt : *S) 773f384594dSTobias Grosser for (auto &Acc : Stmt) 774f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 775f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 776f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 777f384594dSTobias Grosser 778f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 779f384594dSTobias Grosser Space = isl_space_range(Space); 780f384594dSTobias Grosser Space = isl_space_from_range(Space); 7816293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 782f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 783f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 784f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 785f384594dSTobias Grosser } 786f384594dSTobias Grosser 787f384594dSTobias Grosser return Accesses; 788f384594dSTobias Grosser } 789f384594dSTobias Grosser 790f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 791f384594dSTobias Grosser /// 792f384594dSTobias Grosser /// @see getTaggedAccesses 793f384594dSTobias Grosser isl_union_map *getTaggedReads() { 794f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 795f384594dSTobias Grosser } 796f384594dSTobias Grosser 797f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 798f384594dSTobias Grosser /// 799f384594dSTobias Grosser /// @see getTaggedAccesses 800f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 801f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 802f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 803f384594dSTobias Grosser } 804f384594dSTobias Grosser 805f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 806f384594dSTobias Grosser /// 807f384594dSTobias Grosser /// @see getTaggedAccesses 808f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 809f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 810f384594dSTobias Grosser } 811f384594dSTobias Grosser 812aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 813aef5196fSTobias Grosser /// 814aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 815aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 816aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 817aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 818aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 819aef5196fSTobias Grosser /// the data format that ppcg expects. 820aef5196fSTobias Grosser /// 821aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 822aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 823aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 824bd81a7eeSTobias Grosser S->getIslCtx(), 825bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 826aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 827aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 828aef5196fSTobias Grosser 829aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 830aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 831aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 832aef5196fSTobias Grosser } 833aef5196fSTobias Grosser 834aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 835aef5196fSTobias Grosser auto Id = Array.second->getBasePtrId(); 836aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 837aef5196fSTobias Grosser } 838aef5196fSTobias Grosser 839aef5196fSTobias Grosser isl_space_free(Space); 840aef5196fSTobias Grosser isl_ast_expr_free(Zero); 841aef5196fSTobias Grosser 842aef5196fSTobias Grosser return Names; 843aef5196fSTobias Grosser } 844aef5196fSTobias Grosser 845e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 846e938517eSTobias Grosser /// 847f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 848f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 849f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 850f384594dSTobias Grosser /// the PPCG default behaviour more closely. 851e938517eSTobias Grosser /// 852e938517eSTobias Grosser /// @returns A new ppcg scop. 853e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 854e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 855e938517eSTobias Grosser 856e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 857e938517eSTobias Grosser 858e938517eSTobias Grosser PPCGScop->start = 0; 859e938517eSTobias Grosser PPCGScop->end = 0; 860e938517eSTobias Grosser 861f384594dSTobias Grosser PPCGScop->context = S->getContext(); 862f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 863e938517eSTobias Grosser PPCGScop->call = nullptr; 864f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 865f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 866e938517eSTobias Grosser PPCGScop->live_in = nullptr; 867f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 868f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 869f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 870f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 871e938517eSTobias Grosser PPCGScop->live_out = nullptr; 872f384594dSTobias Grosser PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace()); 873e938517eSTobias Grosser PPCGScop->tagger = nullptr; 874e938517eSTobias Grosser 875e938517eSTobias Grosser PPCGScop->independence = nullptr; 876e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 877e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 878e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 879e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 880e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 881e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 882e938517eSTobias Grosser 883f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 884aef5196fSTobias Grosser PPCGScop->names = getNames(); 885e938517eSTobias Grosser 886e938517eSTobias Grosser PPCGScop->pet = nullptr; 887e938517eSTobias Grosser 888f384594dSTobias Grosser compute_tagger(PPCGScop); 889f384594dSTobias Grosser compute_dependences(PPCGScop); 890f384594dSTobias Grosser 891e938517eSTobias Grosser return PPCGScop; 892e938517eSTobias Grosser } 893e938517eSTobias Grosser 89460f63b49STobias Grosser /// Collect the array acesses in a statement. 89560f63b49STobias Grosser /// 89660f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 89760f63b49STobias Grosser /// 89860f63b49STobias Grosser /// @returns A list of array accesses. 89960f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 90060f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 90160f63b49STobias Grosser 90260f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 90360f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 90460f63b49STobias Grosser Access->read = Acc->isRead(); 90560f63b49STobias Grosser Access->write = Acc->isWrite(); 90660f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 90760f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 90860f63b49STobias Grosser Space = isl_space_range(Space); 90960f63b49STobias Grosser Space = isl_space_from_range(Space); 9106293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 91160f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 91260f63b49STobias Grosser Access->tagged_access = 91360f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 91460f63b49STobias Grosser Access->exact_write = Acc->isWrite(); 91560f63b49STobias Grosser Access->ref_id = Acc->getId(); 91660f63b49STobias Grosser Access->next = Accesses; 91760f63b49STobias Grosser Accesses = Access; 91860f63b49STobias Grosser } 91960f63b49STobias Grosser 92060f63b49STobias Grosser return Accesses; 92160f63b49STobias Grosser } 92260f63b49STobias Grosser 92369b46751STobias Grosser /// Collect the list of GPU statements. 92469b46751STobias Grosser /// 92569b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 92669b46751STobias Grosser /// as well as a list with all memory accesses. 92769b46751STobias Grosser /// 92869b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 92969b46751STobias Grosser /// 93069b46751STobias Grosser /// @returns A linked-list of statements. 93169b46751STobias Grosser gpu_stmt *getStatements() { 93269b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 93369b46751STobias Grosser std::distance(S->begin(), S->end())); 93469b46751STobias Grosser 93569b46751STobias Grosser int i = 0; 93669b46751STobias Grosser for (auto &Stmt : *S) { 93769b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 93869b46751STobias Grosser 93969b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 94069b46751STobias Grosser 94169b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 94269b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 94360f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 94469b46751STobias Grosser i++; 94569b46751STobias Grosser } 94669b46751STobias Grosser 94769b46751STobias Grosser return Stmts; 94869b46751STobias Grosser } 94969b46751STobias Grosser 95060f63b49STobias Grosser /// Derive the extent of an array. 95160f63b49STobias Grosser /// 95260f63b49STobias Grosser /// The extent of an array is defined by the set of memory locations for 95360f63b49STobias Grosser /// which a memory access in the iteration domain exists. 95460f63b49STobias Grosser /// 95560f63b49STobias Grosser /// @param Array The array to derive the extent for. 95660f63b49STobias Grosser /// 95760f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 95860f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 95960f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 96060f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 96160f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 96260f63b49STobias Grosser isl_set *AccessSet = 96360f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 96460f63b49STobias Grosser isl_union_set_free(AccessUSet); 96560f63b49STobias Grosser 96660f63b49STobias Grosser return AccessSet; 96760f63b49STobias Grosser } 96860f63b49STobias Grosser 96960f63b49STobias Grosser /// Derive the bounds of an array. 97060f63b49STobias Grosser /// 97160f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 97260f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 97360f63b49STobias Grosser /// ScopArrayInfo. 97460f63b49STobias Grosser /// 97560f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 97660f63b49STobias Grosser /// @param Array The polly array from which to take the information. 97760f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 97860f63b49STobias Grosser if (PPCGArray.n_index > 0) { 97960f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 98060f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 98160f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 98260f63b49STobias Grosser isl_set_free(Dom); 98360f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 98460f63b49STobias Grosser isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom)); 98560f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 98660f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 98760f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 98860f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 98960f63b49STobias Grosser PPCGArray.bound[0] = Bound; 99060f63b49STobias Grosser } 99160f63b49STobias Grosser 99260f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 99360f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 99460f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 99560f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 99660f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 99760f63b49STobias Grosser PPCGArray.bound[i] = Bound; 99860f63b49STobias Grosser } 99960f63b49STobias Grosser } 100060f63b49STobias Grosser 100160f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 100260f63b49STobias Grosser /// 100360f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 100460f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 100560f63b49STobias Grosser int i = 0; 100660f63b49STobias Grosser for (auto &Element : S->arrays()) { 100760f63b49STobias Grosser ScopArrayInfo *Array = Element.second.get(); 100860f63b49STobias Grosser 100960f63b49STobias Grosser std::string TypeName; 101060f63b49STobias Grosser raw_string_ostream OS(TypeName); 101160f63b49STobias Grosser 101260f63b49STobias Grosser OS << *Array->getElementType(); 101360f63b49STobias Grosser TypeName = OS.str(); 101460f63b49STobias Grosser 101560f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 101660f63b49STobias Grosser 101760f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 101860f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 101960f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 102060f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 102160f63b49STobias Grosser PPCGArray.extent = nullptr; 102260f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 102360f63b49STobias Grosser PPCGArray.bound = 102460f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 102560f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 102660f63b49STobias Grosser PPCGArray.n_ref = 0; 102760f63b49STobias Grosser PPCGArray.refs = nullptr; 102860f63b49STobias Grosser PPCGArray.accessed = true; 102960f63b49STobias Grosser PPCGArray.read_only_scalar = false; 103060f63b49STobias Grosser PPCGArray.has_compound_element = false; 103160f63b49STobias Grosser PPCGArray.local = false; 103260f63b49STobias Grosser PPCGArray.declare_local = false; 103360f63b49STobias Grosser PPCGArray.global = false; 103460f63b49STobias Grosser PPCGArray.linearize = false; 103560f63b49STobias Grosser PPCGArray.dep_order = nullptr; 103660f63b49STobias Grosser 103760f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 10382d010dafSTobias Grosser i++; 1039b9fc860aSTobias Grosser 1040b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 104160f63b49STobias Grosser } 104260f63b49STobias Grosser } 104360f63b49STobias Grosser 104460f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 104560f63b49STobias Grosser /// 104660f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 104760f63b49STobias Grosser isl_union_map *getArrayIdentity() { 104860f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 104960f63b49STobias Grosser 105060f63b49STobias Grosser for (auto &Item : S->arrays()) { 105160f63b49STobias Grosser ScopArrayInfo *Array = Item.second.get(); 105260f63b49STobias Grosser isl_space *Space = Array->getSpace(); 105360f63b49STobias Grosser Space = isl_space_map_from_set(Space); 105460f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 105560f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 105660f63b49STobias Grosser } 105760f63b49STobias Grosser 105860f63b49STobias Grosser return Maps; 105960f63b49STobias Grosser } 106060f63b49STobias Grosser 1061e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 1062e938517eSTobias Grosser /// 1063e938517eSTobias Grosser /// @returns A new gpu grogram description. 1064e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 1065e938517eSTobias Grosser 1066e938517eSTobias Grosser if (!PPCGScop) 1067e938517eSTobias Grosser return nullptr; 1068e938517eSTobias Grosser 1069e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 1070e938517eSTobias Grosser 1071e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 1072e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 1073aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 107460f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 107560f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 107660f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 107760f63b49STobias Grosser PPCGProg->tagged_must_kill = 107860f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 107960f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 108060f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 108160f63b49STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 1082e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 1083e938517eSTobias Grosser PPCGProg->array_order = nullptr; 108469b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 108569b46751STobias Grosser PPCGProg->stmts = getStatements(); 108660f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 108760f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 108860f63b49STobias Grosser PPCGProg->n_array); 108960f63b49STobias Grosser 109060f63b49STobias Grosser createArrays(PPCGProg); 1091e938517eSTobias Grosser 1092e938517eSTobias Grosser return PPCGProg; 1093e938517eSTobias Grosser } 1094e938517eSTobias Grosser 109569b46751STobias Grosser struct PrintGPUUserData { 109669b46751STobias Grosser struct cuda_info *CudaInfo; 109769b46751STobias Grosser struct gpu_prog *PPCGProg; 109869b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 109969b46751STobias Grosser }; 110069b46751STobias Grosser 110169b46751STobias Grosser /// Print a user statement node in the host code. 110269b46751STobias Grosser /// 110369b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 110469b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 110569b46751STobias Grosser /// host ast. 110669b46751STobias Grosser /// 110769b46751STobias Grosser /// @param P The printer to print to 110869b46751STobias Grosser /// @param Options The printing options to use 110969b46751STobias Grosser /// @param Node The node to print 111069b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 111169b46751STobias Grosser /// expected to be of type PrintGPUUserData. 111269b46751STobias Grosser /// 111369b46751STobias Grosser /// @returns A printer to which the output has been printed. 111469b46751STobias Grosser static __isl_give isl_printer * 111569b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 111669b46751STobias Grosser __isl_take isl_ast_print_options *Options, 111769b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 111869b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 111969b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 112069b46751STobias Grosser 112169b46751STobias Grosser if (Id) { 112220251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 112320251734STobias Grosser 112420251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 112520251734STobias Grosser // otherwise try to call pet functionality that is not available in 112620251734STobias Grosser // Polly. 112720251734STobias Grosser if (IsUser) { 112820251734STobias Grosser P = isl_printer_start_line(P); 112920251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 113020251734STobias Grosser P = isl_printer_end_line(P); 113120251734STobias Grosser isl_id_free(Id); 113220251734STobias Grosser isl_ast_print_options_free(Options); 113320251734STobias Grosser return P; 113420251734STobias Grosser } 113520251734STobias Grosser 113669b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 113769b46751STobias Grosser isl_id_free(Id); 113869b46751STobias Grosser Data->Kernels.push_back(Kernel); 113969b46751STobias Grosser } 114069b46751STobias Grosser 114169b46751STobias Grosser return print_host_user(P, Options, Node, User); 114269b46751STobias Grosser } 114369b46751STobias Grosser 114469b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 114569b46751STobias Grosser /// 114669b46751STobias Grosser /// @param Kernel The kernel to print 114769b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 114869b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 114969b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 115069b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 115169b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 115269b46751STobias Grosser char *String = isl_printer_get_str(P); 115369b46751STobias Grosser printf("%s\n", String); 115469b46751STobias Grosser free(String); 115569b46751STobias Grosser isl_printer_free(P); 115669b46751STobias Grosser } 115769b46751STobias Grosser 115869b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 115969b46751STobias Grosser /// 116069b46751STobias Grosser /// @param Tree An AST describing GPU code 116169b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 116269b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 116369b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 116469b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 116569b46751STobias Grosser 116669b46751STobias Grosser PrintGPUUserData Data; 116769b46751STobias Grosser Data.PPCGProg = PPCGProg; 116869b46751STobias Grosser 116969b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 117069b46751STobias Grosser Options = 117169b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 117269b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 117369b46751STobias Grosser char *String = isl_printer_get_str(P); 117469b46751STobias Grosser printf("# host\n"); 117569b46751STobias Grosser printf("%s\n", String); 117669b46751STobias Grosser free(String); 117769b46751STobias Grosser isl_printer_free(P); 117869b46751STobias Grosser 117969b46751STobias Grosser for (auto Kernel : Data.Kernels) { 118069b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 118169b46751STobias Grosser printKernel(Kernel); 118269b46751STobias Grosser } 118369b46751STobias Grosser } 118469b46751STobias Grosser 1185f384594dSTobias Grosser // Generate a GPU program using PPCG. 1186f384594dSTobias Grosser // 1187f384594dSTobias Grosser // GPU mapping consists of multiple steps: 1188f384594dSTobias Grosser // 1189f384594dSTobias Grosser // 1) Compute new schedule for the program. 1190f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 1191f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 1192f384594dSTobias Grosser // 1193f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 1194f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 1195f384594dSTobias Grosser // strategy directly from this pass. 1196f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 1197f384594dSTobias Grosser 1198f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 1199f384594dSTobias Grosser 1200f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 1201f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 1202f384594dSTobias Grosser PPCGGen->print = nullptr; 1203f384594dSTobias Grosser PPCGGen->print_user = nullptr; 120460c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 1205f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 1206f384594dSTobias Grosser PPCGGen->tree = nullptr; 1207f384594dSTobias Grosser PPCGGen->types.n = 0; 1208f384594dSTobias Grosser PPCGGen->types.name = nullptr; 1209f384594dSTobias Grosser PPCGGen->sizes = nullptr; 1210f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 1211f384594dSTobias Grosser PPCGGen->kernel_id = 0; 1212f384594dSTobias Grosser 1213f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 1214f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 1215f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 12162341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 1217f384594dSTobias Grosser 1218f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 1219f384594dSTobias Grosser 1220aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 1221aef5196fSTobias Grosser 122269b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 1223aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 122469b46751STobias Grosser } else { 1225aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 122669b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 122769b46751STobias Grosser } 1228aef5196fSTobias Grosser 1229f384594dSTobias Grosser if (DumpSchedule) { 1230f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 1231f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 1232f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 1233f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 1234f384594dSTobias Grosser if (Schedule) 1235f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 1236f384594dSTobias Grosser else 1237f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 1238f384594dSTobias Grosser 1239f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 1240f384594dSTobias Grosser isl_printer_free(P); 1241f384594dSTobias Grosser } 1242f384594dSTobias Grosser 124369b46751STobias Grosser if (DumpCode) { 124469b46751STobias Grosser printf("Code\n"); 124569b46751STobias Grosser printf("====\n"); 124669b46751STobias Grosser if (PPCGGen->tree) 124769b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 124869b46751STobias Grosser else 124969b46751STobias Grosser printf("No code generated\n"); 125069b46751STobias Grosser } 125169b46751STobias Grosser 1252f384594dSTobias Grosser isl_schedule_free(Schedule); 1253f384594dSTobias Grosser 1254f384594dSTobias Grosser return PPCGGen; 1255f384594dSTobias Grosser } 1256f384594dSTobias Grosser 1257f384594dSTobias Grosser /// Free gpu_gen structure. 1258f384594dSTobias Grosser /// 1259f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 1260f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 1261f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 1262f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 1263f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 1264f384594dSTobias Grosser free(PPCGGen); 1265f384594dSTobias Grosser } 1266f384594dSTobias Grosser 1267b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 1268b307ed4dSTobias Grosser /// 1269b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 1270b307ed4dSTobias Grosser /// ourselves. 1271b307ed4dSTobias Grosser /// 1272b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 1273b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 1274b307ed4dSTobias Grosser free(PPCGScop->options->debug); 1275b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 1276b307ed4dSTobias Grosser free(PPCGScop->options); 1277b307ed4dSTobias Grosser PPCGScop->options = nullptr; 1278b307ed4dSTobias Grosser } 1279b307ed4dSTobias Grosser 128038fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 128138fc0aedSTobias Grosser /// 128232837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 128332837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 128432837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 128538fc0aedSTobias Grosser ScopAnnotator Annotator; 128638fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 128738fc0aedSTobias Grosser 128838fc0aedSTobias Grosser Region *R = &S->getRegion(); 128938fc0aedSTobias Grosser 129038fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 129138fc0aedSTobias Grosser 129238fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 129338fc0aedSTobias Grosser 129438fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 129538fc0aedSTobias Grosser 129632837fe3STobias Grosser GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S, 129732837fe3STobias Grosser Prog); 129838fc0aedSTobias Grosser 129938fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 130038fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 130138fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 130238fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 130338fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 130438fc0aedSTobias Grosser // code generating this scop. 130538fc0aedSTobias Grosser BasicBlock *StartBlock = 130638fc0aedSTobias Grosser executeScopConditionally(*S, this, Builder.getTrue()); 130738fc0aedSTobias Grosser 130838fc0aedSTobias Grosser // TODO: Handle LICM 130938fc0aedSTobias Grosser // TODO: Verify run-time checks 131038fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 131138fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 131238fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 131338fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 131438fc0aedSTobias Grosser NodeBuilder.create(Root); 131538fc0aedSTobias Grosser NodeBuilder.finalizeSCoP(*S); 131638fc0aedSTobias Grosser } 131738fc0aedSTobias Grosser 1318e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 1319e938517eSTobias Grosser S = &CurrentScop; 132038fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 132138fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 132238fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 132338fc0aedSTobias Grosser DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout(); 132438fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 1325e938517eSTobias Grosser 13262d58a64eSTobias Grosser // We currently do not support scops with invariant loads. 13272d58a64eSTobias Grosser if (S->hasInvariantAccesses()) 13282d58a64eSTobias Grosser return false; 13292d58a64eSTobias Grosser 1330e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 1331e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 1332f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 133338fc0aedSTobias Grosser 133438fc0aedSTobias Grosser if (PPCGGen->tree) 133532837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 133638fc0aedSTobias Grosser 1337b307ed4dSTobias Grosser freeOptions(PPCGScop); 1338f384594dSTobias Grosser freePPCGGen(PPCGGen); 1339e938517eSTobias Grosser gpu_prog_free(PPCGProg); 1340e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 1341e938517eSTobias Grosser 1342e938517eSTobias Grosser return true; 1343e938517eSTobias Grosser } 13449dfe4e7cSTobias Grosser 13459dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 13469dfe4e7cSTobias Grosser 13479dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 13489dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 13499dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 13509dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 13519dfe4e7cSTobias Grosser AU.addRequired<ScopDetection>(); 13529dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 13539dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 13549dfe4e7cSTobias Grosser 13559dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 13569dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 13579dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 13589dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 13599dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 13609dfe4e7cSTobias Grosser AU.addPreserved<PostDominatorTreeWrapperPass>(); 13619dfe4e7cSTobias Grosser AU.addPreserved<ScopDetection>(); 13629dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 13639dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 13649dfe4e7cSTobias Grosser 13659dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 13669dfe4e7cSTobias Grosser // region tree. 13679dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 13689dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 13699dfe4e7cSTobias Grosser } 13709dfe4e7cSTobias Grosser }; 13719dfe4e7cSTobias Grosser } 13729dfe4e7cSTobias Grosser 13739dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 13749dfe4e7cSTobias Grosser 13759dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); } 13769dfe4e7cSTobias Grosser 13779dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 13789dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 13799dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 13809dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 13819dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 13829dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 13839dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 13849dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection); 13859dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 13869dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 1387