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 15*17f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h" 16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 21f384594dSTobias Grosser #include "polly/Options.h" 22629109b6STobias Grosser #include "polly/ScopDetection.h" 239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 33e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 399dfe4e7cSTobias Grosser 40f384594dSTobias Grosser #include "isl/union_map.h" 41f384594dSTobias Grosser 42e938517eSTobias Grosser extern "C" { 43a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 44a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 47a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 48e938517eSTobias Grosser } 49e938517eSTobias Grosser 509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 519dfe4e7cSTobias Grosser 529dfe4e7cSTobias Grosser using namespace polly; 539dfe4e7cSTobias Grosser using namespace llvm; 549dfe4e7cSTobias Grosser 559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 569dfe4e7cSTobias Grosser 57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 58f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 59681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 60f384594dSTobias Grosser cl::cat(PollyCategory)); 6169b46751STobias Grosser 6269b46751STobias Grosser static cl::opt<bool> 6369b46751STobias Grosser DumpCode("polly-acc-dump-code", 6469b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6569b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6669b46751STobias Grosser 6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6832837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6932837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7032837fe3STobias Grosser cl::cat(PollyCategory)); 7132837fe3STobias Grosser 7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7374dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7474dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7574dc3cb4STobias Grosser cl::cat(PollyCategory)); 7674dc3cb4STobias Grosser 7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7874dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7974dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8074dc3cb4STobias Grosser cl::cat(PollyCategory)); 81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 82b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 83b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 84b513b491STobias Grosser cl::cat(PollyCategory)); 85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 86130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 87130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 88130ca30fSTobias Grosser cl::cat(PollyCategory)); 8974dc3cb4STobias Grosser 90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 92abed4969SSiddharth Bhat " that all memory has been" 93abed4969SSiddharth Bhat " declared as managed memory"), 94abed4969SSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 95abed4969SSiddharth Bhat cl::cat(PollyCategory)); 96abed4969SSiddharth Bhat 9774dc3cb4STobias Grosser static cl::opt<std::string> 9874dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 9974dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 10074dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 10174dc3cb4STobias Grosser 10282f2af35STobias Grosser static cl::opt<int> 10382f2af35STobias Grosser MinCompute("polly-acc-mincompute", 10482f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 10582f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 10682f2af35STobias Grosser 10760c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 10860c60025STobias Grosser /// 10960c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 11060c60025STobias Grosser /// of the scheduled ScopStmts. 11160c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 112edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 11360c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 11460c60025STobias Grosser isl_id *Id, void *User), 11560c60025STobias Grosser void *UserIndex, 11660c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 117edb885cbSTobias Grosser void *UserExpr) { 11860c60025STobias Grosser 119edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 12060c60025STobias Grosser 121edb885cbSTobias Grosser isl_ctx *Ctx; 122edb885cbSTobias Grosser 123edb885cbSTobias Grosser if (!Stmt || !Build) 124edb885cbSTobias Grosser return NULL; 125edb885cbSTobias Grosser 126edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 127edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 128edb885cbSTobias Grosser 129edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 130edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 131edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 132edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 133edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 134edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 135edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 136edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 137edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 138edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 139edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 140edb885cbSTobias Grosser } 141edb885cbSTobias Grosser 142edb885cbSTobias Grosser return RefToExpr; 14360c60025STobias Grosser } 144f384594dSTobias Grosser 14538fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 14638fc0aedSTobias Grosser /// 14738fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 14838fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality 14938fc0aedSTobias Grosser /// for generating GPU specific user nodes. 15038fc0aedSTobias Grosser /// 15138fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 15238fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 15338fc0aedSTobias Grosser public: 1542d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 15538fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 156acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 157*17f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 1582d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 159*17f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 160edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 161edb885cbSTobias Grosser } 16238fc0aedSTobias Grosser 163fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 164fa7b0802STobias Grosser void initializeAfterRTH(); 165fa7b0802STobias Grosser 166fa7b0802STobias Grosser /// Finalize the generated scop. 167fa7b0802STobias Grosser virtual void finalize(); 168fa7b0802STobias Grosser 1695857b701STobias Grosser /// Track if the full build process was successful. 1705857b701STobias Grosser /// 1715857b701STobias Grosser /// This value is set to false, if throughout the build process an error 1725857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 1735857b701STobias Grosser bool BuildSuccessful = true; 1745857b701STobias Grosser 175bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 176bc653f20STobias Grosser unsigned DeepestSequential = 0; 177bc653f20STobias Grosser 178bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 179bc653f20STobias Grosser unsigned DeepestParallel = 0; 180bc653f20STobias Grosser 18138fc0aedSTobias Grosser private: 18274dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 18374dc3cb4STobias Grosser /// 18474dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 18574dc3cb4STobias Grosser /// more. 18674dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 18774dc3cb4STobias Grosser 18813c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 18913c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 1907287aeddSTobias Grosser 191fa7b0802STobias Grosser /// The current GPU context. 192fa7b0802STobias Grosser Value *GPUContext; 193fa7b0802STobias Grosser 194b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 195b513b491STobias Grosser std::vector<isl_id *> KernelIds; 196b513b491STobias Grosser 19732837fe3STobias Grosser /// A module containing GPU code. 19832837fe3STobias Grosser /// 19932837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 20032837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 20132837fe3STobias Grosser 20232837fe3STobias Grosser /// The GPU program we generate code for. 20332837fe3STobias Grosser gpu_prog *Prog; 20432837fe3STobias Grosser 205*17f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 206*17f01968SSiddharth Bhat GPURuntime Runtime; 207*17f01968SSiddharth Bhat 208*17f01968SSiddharth Bhat /// The GPU Architecture to target. 209*17f01968SSiddharth Bhat GPUArch Arch; 210*17f01968SSiddharth Bhat 211472f9654STobias Grosser /// Class to free isl_ids. 212472f9654STobias Grosser class IslIdDeleter { 213472f9654STobias Grosser public: 214472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 215472f9654STobias Grosser }; 216472f9654STobias Grosser 217472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 218472f9654STobias Grosser /// 219472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 220472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 221472f9654STobias Grosser 222edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 223edb885cbSTobias Grosser 22438fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 22538fc0aedSTobias Grosser /// 22638fc0aedSTobias Grosser /// These AST nodes can be of type: 22738fc0aedSTobias Grosser /// 22838fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 22938fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 23013c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 2315260c041STobias Grosser /// - In-kernel synchronization 2325260c041STobias Grosser /// - In-kernel memory copy statement 23338fc0aedSTobias Grosser /// 2341fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 2351fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 23632837fe3STobias Grosser 23713c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 23813c78e4dSTobias Grosser 23913c78e4dSTobias Grosser /// Create code for a data transfer statement 24013c78e4dSTobias Grosser /// 24113c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 24213c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 24313c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 24413c78e4dSTobias Grosser enum DataDirection Direction); 24513c78e4dSTobias Grosser 246edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 247edb885cbSTobias Grosser /// 248edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 249edb885cbSTobias Grosser /// 250edb885cbSTobias Grosser /// @returns A set of values referenced by the kernel. 251edb885cbSTobias Grosser SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel); 252edb885cbSTobias Grosser 25379a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 25479a947c2STobias Grosser /// 25579a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 25679a947c2STobias Grosser /// 25779a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 25879a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 25979a947c2STobias Grosser 260abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 261abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 262abed4969SSiddharth Bhat /// host pointers to the device. 263abed4969SSiddharth Bhat /// \note 264abed4969SSiddharth Bhat /// This is to be used only with managed memory 265abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 266abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 267abed4969SSiddharth Bhat 26879a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 26979a947c2STobias Grosser /// 27079a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 27179a947c2STobias Grosser /// 27279a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 27379a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 27479a947c2STobias Grosser 27579a947c2STobias Grosser /// Create kernel launch parameters. 27679a947c2STobias Grosser /// 27779a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 27879a947c2STobias Grosser /// @param F The kernel function that has been created. 27957693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 28079a947c2STobias Grosser /// 28179a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 28279a947c2STobias Grosser /// values that are passed to the kernel. 28357693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 28457693272STobias Grosser SetVector<Value *> SubtreeValues); 28579a947c2STobias Grosser 286b513b491STobias Grosser /// Create declarations for kernel variable. 287b513b491STobias Grosser /// 288b513b491STobias Grosser /// This includes shared memory declarations. 289b513b491STobias Grosser /// 290b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 291b513b491STobias Grosser /// @param FN The function into which to generate the variables. 292b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 293b513b491STobias Grosser 294c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 295c1c6a2a6STobias Grosser /// 296c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 297c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 298c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 299c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 300c1c6a2a6STobias Grosser /// as specified here. 301c1c6a2a6STobias Grosser /// 302c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 303c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 304c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 305c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 306c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 307c1c6a2a6STobias Grosser Value *BlockDimZ); 308c1c6a2a6STobias Grosser 30932837fe3STobias Grosser /// Create GPU kernel. 31032837fe3STobias Grosser /// 31132837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 31232837fe3STobias Grosser /// 31332837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 31432837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 31532837fe3STobias Grosser 31613c78e4dSTobias Grosser /// Generate code that computes the size of an array. 31713c78e4dSTobias Grosser /// 31813c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 31913c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 32013c78e4dSTobias Grosser 321aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 322aaabbbf8STobias Grosser /// 323aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 324aaabbbf8STobias Grosser /// 325aaabbbf8STobias Grosser /// Example: 326aaabbbf8STobias Grosser /// 327aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 328aaabbbf8STobias Grosser /// A[i + 42] += ... 329aaabbbf8STobias Grosser /// 330aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 331aaabbbf8STobias Grosser /// 332aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 333aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 334aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 335aaabbbf8STobias Grosser 33600bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 33700bb5a99STobias Grosser /// 33800bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 33900bb5a99STobias Grosser /// @param FN The function created for the kernel. 34000bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 34100bb5a99STobias Grosser 34232837fe3STobias Grosser /// Create kernel function. 34332837fe3STobias Grosser /// 34432837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 34532837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 34632837fe3STobias Grosser /// start block of this newly created function. 34732837fe3STobias Grosser /// 34832837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 349edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 350edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 351edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 35232837fe3STobias Grosser 35332837fe3STobias Grosser /// Create the declaration of a kernel function. 35432837fe3STobias Grosser /// 35532837fe3STobias Grosser /// The kernel function takes as arguments: 35632837fe3STobias Grosser /// 35732837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 358f6044bd0STobias Grosser /// - Host iterators 359c84a1995STobias Grosser /// - Parameters 36032837fe3STobias Grosser /// - Other LLVM Value references (TODO) 36132837fe3STobias Grosser /// 36232837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 363edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 364edb885cbSTobias Grosser /// 36532837fe3STobias Grosser /// @returns The newly declared function. 366edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 367edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 36832837fe3STobias Grosser 369472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 370472f9654STobias Grosser /// 371472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 372472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 373472f9654STobias Grosser 374b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 375b513b491STobias Grosser /// 376b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 377b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 378b513b491STobias Grosser 379edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 380edb885cbSTobias Grosser /// 381edb885cbSTobias Grosser /// @param Expr The expression containing the call. 382edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 383edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 384edb885cbSTobias Grosser 3855260c041STobias Grosser /// Create an in-kernel synchronization call. 3865260c041STobias Grosser void createKernelSync(); 3875260c041STobias Grosser 38874dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 38974dc3cb4STobias Grosser /// 39074dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 39174dc3cb4STobias Grosser std::string createKernelASM(); 39274dc3cb4STobias Grosser 39374dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 39474dc3cb4STobias Grosser /// 39574dc3cb4STobias Grosser /// @param F The function to remove references to. 39674dc3cb4STobias Grosser void clearDominators(Function *F); 39774dc3cb4STobias Grosser 39874dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 39974dc3cb4STobias Grosser /// 40074dc3cb4STobias Grosser /// @param F The function to remove references to. 40174dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 40274dc3cb4STobias Grosser 40374dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 40474dc3cb4STobias Grosser /// 40574dc3cb4STobias Grosser /// @param F The function to remove references to. 40674dc3cb4STobias Grosser void clearLoops(Function *F); 40774dc3cb4STobias Grosser 40832837fe3STobias Grosser /// Finalize the generation of the kernel function. 40932837fe3STobias Grosser /// 41032837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 41132837fe3STobias Grosser /// dump its IR to stderr. 41257793596STobias Grosser /// 41357793596STobias Grosser /// @returns The Assembly string of the kernel. 41457793596STobias Grosser std::string finalizeKernelFunction(); 415fa7b0802STobias Grosser 41651dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 41751dfc275STobias Grosser /// 41851dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 41951dfc275STobias Grosser /// stored back to the global memory location they ared backed up with before 42051dfc275STobias Grosser /// the kernel terminates. 42151dfc275STobias Grosser /// 42251dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 42351dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 42451dfc275STobias Grosser 4257287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 426fa7b0802STobias Grosser void allocateDeviceArrays(); 427fa7b0802STobias Grosser 4287287aeddSTobias Grosser /// Free all allocated device arrays. 4297287aeddSTobias Grosser void freeDeviceArrays(); 4307287aeddSTobias Grosser 431fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 432fa7b0802STobias Grosser /// 433fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 434fa7b0802STobias Grosser Value *createCallInitContext(); 435fa7b0802STobias Grosser 43679a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 43779a947c2STobias Grosser /// 43879a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 43979a947c2STobias Grosser /// 44079a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 44179a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 44279a947c2STobias Grosser 443fa7b0802STobias Grosser /// Create a call to free the GPU context. 444fa7b0802STobias Grosser /// 445fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 446fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 447fa7b0802STobias Grosser 4487287aeddSTobias Grosser /// Create a call to allocate memory on the device. 4497287aeddSTobias Grosser /// 4507287aeddSTobias Grosser /// @param Size The size of memory to allocate 4517287aeddSTobias Grosser /// 4527287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 453fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 4547287aeddSTobias Grosser 4557287aeddSTobias Grosser /// Create a call to free a device array. 4567287aeddSTobias Grosser /// 4577287aeddSTobias Grosser /// @param Array The device array to free. 4587287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 45913c78e4dSTobias Grosser 46013c78e4dSTobias Grosser /// Create a call to copy data from host to device. 46113c78e4dSTobias Grosser /// 46213c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 46313c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 46413c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 46513c78e4dSTobias Grosser Value *Size); 46613c78e4dSTobias Grosser 46713c78e4dSTobias Grosser /// Create a call to copy data from device to host. 46813c78e4dSTobias Grosser /// 46913c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 47013c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 47113c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 47213c78e4dSTobias Grosser Value *Size); 47357793596STobias Grosser 474abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 475abed4969SSiddharth Bhat /// \note 476abed4969SSiddharth Bhat /// This is to be used only with managed memory. 477abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 478abed4969SSiddharth Bhat 47957793596STobias Grosser /// Create a call to get a kernel from an assembly string. 48057793596STobias Grosser /// 48157793596STobias Grosser /// @param Buffer The string describing the kernel. 48257793596STobias Grosser /// @param Entry The name of the kernel function to call. 48357793596STobias Grosser /// 48457793596STobias Grosser /// @returns A pointer to a kernel object 48557793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 48657793596STobias Grosser 48757793596STobias Grosser /// Create a call to free a GPU kernel. 48857793596STobias Grosser /// 48957793596STobias Grosser /// @param GPUKernel THe kernel to free. 49057793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 49179a947c2STobias Grosser 49279a947c2STobias Grosser /// Create a call to launch a GPU kernel. 49379a947c2STobias Grosser /// 49479a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 49579a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 49679a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 49779a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 49879a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 49979a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 50079a947c2STobias Grosser /// @param Paramters A pointer to an array that contains itself pointers to 50179a947c2STobias Grosser /// the parameter values passed for each kernel argument. 50279a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 50379a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 50479a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 50579a947c2STobias Grosser Value *Parameters); 5061fb9b64dSTobias Grosser }; 5071fb9b64dSTobias Grosser 508fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 509750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 510750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 511750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 512750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 513750160e2STobias Grosser 514fa7b0802STobias Grosser GPUContext = createCallInitContext(); 515abed4969SSiddharth Bhat 516abed4969SSiddharth Bhat if (!ManagedMemory) 517fa7b0802STobias Grosser allocateDeviceArrays(); 518fa7b0802STobias Grosser } 519fa7b0802STobias Grosser 520fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 521abed4969SSiddharth Bhat if (!ManagedMemory) 5227287aeddSTobias Grosser freeDeviceArrays(); 523abed4969SSiddharth Bhat 524fa7b0802STobias Grosser createCallFreeContext(GPUContext); 525fa7b0802STobias Grosser IslNodeBuilder::finalize(); 526fa7b0802STobias Grosser } 527fa7b0802STobias Grosser 528fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 529abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 530abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 531fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 532fa7b0802STobias Grosser 533fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 534fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 53513c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 5367287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 5377287aeddSTobias Grosser DevArrayName.append(Array->name); 538fa7b0802STobias Grosser 53913c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 540aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 541aaabbbf8STobias Grosser if (Offset) 542aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 543aaabbbf8STobias Grosser ArraySize, 544aaabbbf8STobias Grosser Builder.CreateMul(Offset, 545aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 5467287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 5477287aeddSTobias Grosser DevArray->setName(DevArrayName); 54813c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 549fa7b0802STobias Grosser } 550fa7b0802STobias Grosser 551fa7b0802STobias Grosser isl_ast_build_free(Build); 552fa7b0802STobias Grosser } 553fa7b0802STobias Grosser 554c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 555c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 556c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 557c1c6a2a6STobias Grosser 558c1c6a2a6STobias Grosser for (auto &F : *M) { 559c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 560c1c6a2a6STobias Grosser continue; 561c1c6a2a6STobias Grosser 562c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 563c1c6a2a6STobias Grosser 564c1c6a2a6STobias Grosser Metadata *Elements[] = { 565c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 566c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 567c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 568c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 569c1c6a2a6STobias Grosser }; 570c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 571c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 572c1c6a2a6STobias Grosser } 573c1c6a2a6STobias Grosser } 574c1c6a2a6STobias Grosser 5757287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 576abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 57713c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 57813c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 5797287aeddSTobias Grosser } 5807287aeddSTobias Grosser 58157793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 58257793596STobias Grosser const char *Name = "polly_getKernel"; 58357793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 58457793596STobias Grosser Function *F = M->getFunction(Name); 58557793596STobias Grosser 58657793596STobias Grosser // If F is not available, declare it. 58757793596STobias Grosser if (!F) { 58857793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 58957793596STobias Grosser std::vector<Type *> Args; 59057793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 59157793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 59257793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 59357793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 59457793596STobias Grosser } 59557793596STobias Grosser 59657793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 59757793596STobias Grosser } 59857793596STobias Grosser 59979a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 60079a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 60179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 60279a947c2STobias Grosser Function *F = M->getFunction(Name); 60379a947c2STobias Grosser 60479a947c2STobias Grosser // If F is not available, declare it. 60579a947c2STobias Grosser if (!F) { 60679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 60779a947c2STobias Grosser std::vector<Type *> Args; 60879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 60979a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 61079a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 61179a947c2STobias Grosser } 61279a947c2STobias Grosser 61379a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 61479a947c2STobias Grosser } 61579a947c2STobias Grosser 61679a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 61779a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 61879a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 61979a947c2STobias Grosser Value *Parameters) { 62079a947c2STobias Grosser const char *Name = "polly_launchKernel"; 62179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 62279a947c2STobias Grosser Function *F = M->getFunction(Name); 62379a947c2STobias Grosser 62479a947c2STobias Grosser // If F is not available, declare it. 62579a947c2STobias Grosser if (!F) { 62679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 62779a947c2STobias Grosser std::vector<Type *> Args; 62879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 62979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 63079a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 63179a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 63279a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 63379a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 63479a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 63579a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 63679a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 63779a947c2STobias Grosser } 63879a947c2STobias Grosser 639ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 64079a947c2STobias Grosser BlockDimZ, Parameters}); 64179a947c2STobias Grosser } 64279a947c2STobias Grosser 64357793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 64457793596STobias Grosser const char *Name = "polly_freeKernel"; 64557793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 64657793596STobias Grosser Function *F = M->getFunction(Name); 64757793596STobias Grosser 64857793596STobias Grosser // If F is not available, declare it. 64957793596STobias Grosser if (!F) { 65057793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 65157793596STobias Grosser std::vector<Type *> Args; 65257793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 65357793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 65457793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 65557793596STobias Grosser } 65657793596STobias Grosser 65757793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 65857793596STobias Grosser } 65957793596STobias Grosser 6607287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 661abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 662abed4969SSiddharth Bhat "for device"); 6637287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 6647287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 6657287aeddSTobias Grosser Function *F = M->getFunction(Name); 6667287aeddSTobias Grosser 6677287aeddSTobias Grosser // If F is not available, declare it. 6687287aeddSTobias Grosser if (!F) { 6697287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 6707287aeddSTobias Grosser std::vector<Type *> Args; 6717287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 6727287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 6737287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 6747287aeddSTobias Grosser } 6757287aeddSTobias Grosser 6767287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 6777287aeddSTobias Grosser } 6787287aeddSTobias Grosser 679fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 680abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 681abed4969SSiddharth Bhat "for device"); 682fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 683fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 684fa7b0802STobias Grosser Function *F = M->getFunction(Name); 685fa7b0802STobias Grosser 686fa7b0802STobias Grosser // If F is not available, declare it. 687fa7b0802STobias Grosser if (!F) { 688fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 689fa7b0802STobias Grosser std::vector<Type *> Args; 690fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 691fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 692fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 693fa7b0802STobias Grosser } 694fa7b0802STobias Grosser 695fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 696fa7b0802STobias Grosser } 697fa7b0802STobias Grosser 69813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 69913c78e4dSTobias Grosser Value *DeviceData, 70013c78e4dSTobias Grosser Value *Size) { 701abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 702abed4969SSiddharth Bhat "device and host"); 70313c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 70413c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 70513c78e4dSTobias Grosser Function *F = M->getFunction(Name); 70613c78e4dSTobias Grosser 70713c78e4dSTobias Grosser // If F is not available, declare it. 70813c78e4dSTobias Grosser if (!F) { 70913c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 71013c78e4dSTobias Grosser std::vector<Type *> Args; 71113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 71213c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 71313c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 71413c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 71513c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 71613c78e4dSTobias Grosser } 71713c78e4dSTobias Grosser 71813c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 71913c78e4dSTobias Grosser } 72013c78e4dSTobias Grosser 72113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 72213c78e4dSTobias Grosser Value *HostData, 72313c78e4dSTobias Grosser Value *Size) { 724abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 725abed4969SSiddharth Bhat "device and host"); 72613c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 72713c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 72813c78e4dSTobias Grosser Function *F = M->getFunction(Name); 72913c78e4dSTobias Grosser 73013c78e4dSTobias Grosser // If F is not available, declare it. 73113c78e4dSTobias Grosser if (!F) { 73213c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 73313c78e4dSTobias Grosser std::vector<Type *> Args; 73413c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 73513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 73613c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 73713c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 73813c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 73913c78e4dSTobias Grosser } 74013c78e4dSTobias Grosser 74113c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 74213c78e4dSTobias Grosser } 74313c78e4dSTobias Grosser 744abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 745abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 746abed4969SSiddharth Bhat "managed memory"); 747abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 748abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 749abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 750abed4969SSiddharth Bhat 751abed4969SSiddharth Bhat // If F is not available, declare it. 752abed4969SSiddharth Bhat if (!F) { 753abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 754abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 755abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 756abed4969SSiddharth Bhat } 757abed4969SSiddharth Bhat 758abed4969SSiddharth Bhat Builder.CreateCall(F); 759abed4969SSiddharth Bhat } 760abed4969SSiddharth Bhat 761fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 762*17f01968SSiddharth Bhat const char *Name; 763*17f01968SSiddharth Bhat 764*17f01968SSiddharth Bhat switch (Runtime) { 765*17f01968SSiddharth Bhat case GPURuntime::CUDA: 766*17f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 767*17f01968SSiddharth Bhat break; 768*17f01968SSiddharth Bhat case GPURuntime::OpenCL: 769*17f01968SSiddharth Bhat Name = "polly_initContextCL"; 770*17f01968SSiddharth Bhat break; 771*17f01968SSiddharth Bhat } 772*17f01968SSiddharth Bhat 773fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 774fa7b0802STobias Grosser Function *F = M->getFunction(Name); 775fa7b0802STobias Grosser 776fa7b0802STobias Grosser // If F is not available, declare it. 777fa7b0802STobias Grosser if (!F) { 778fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 779fa7b0802STobias Grosser std::vector<Type *> Args; 780fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 781fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 782fa7b0802STobias Grosser } 783fa7b0802STobias Grosser 784fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 785fa7b0802STobias Grosser } 786fa7b0802STobias Grosser 787fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 788fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 789fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 790fa7b0802STobias Grosser Function *F = M->getFunction(Name); 791fa7b0802STobias Grosser 792fa7b0802STobias Grosser // If F is not available, declare it. 793fa7b0802STobias Grosser if (!F) { 794fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 795fa7b0802STobias Grosser std::vector<Type *> Args; 796fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 797fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 798fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 799fa7b0802STobias Grosser } 800fa7b0802STobias Grosser 801fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 802fa7b0802STobias Grosser } 803fa7b0802STobias Grosser 8045260c041STobias Grosser /// Check if one string is a prefix of another. 8055260c041STobias Grosser /// 8065260c041STobias Grosser /// @param String The string in which to look for the prefix. 8075260c041STobias Grosser /// @param Prefix The prefix to look for. 8085260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 8095260c041STobias Grosser return String.find(Prefix) == 0; 8105260c041STobias Grosser } 8115260c041STobias Grosser 81213c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 81313c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 81413c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 81513c78e4dSTobias Grosser 81613c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 81713c78e4dSTobias Grosser auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 81813c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 81913c78e4dSTobias Grosser 82013c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 82113c78e4dSTobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 82213c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 82313c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 82413c78e4dSTobias Grosser } 82513c78e4dSTobias Grosser 82613c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 827b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 828b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 82913c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 83013c78e4dSTobias Grosser } 83113c78e4dSTobias Grosser isl_ast_build_free(Build); 83213c78e4dSTobias Grosser return ArraySize; 83313c78e4dSTobias Grosser } 83413c78e4dSTobias Grosser 835aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 836aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 837aaabbbf8STobias Grosser return nullptr; 838aaabbbf8STobias Grosser 839aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 840aaabbbf8STobias Grosser 841aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 842aaabbbf8STobias Grosser 843aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 844aaabbbf8STobias Grosser 845aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 846aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 847aaabbbf8STobias Grosser 848aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 849aaabbbf8STobias Grosser isl_set_free(Min); 850aaabbbf8STobias Grosser isl_set_free(ZeroSet); 851aaabbbf8STobias Grosser isl_ast_build_free(Build); 852aaabbbf8STobias Grosser return nullptr; 853aaabbbf8STobias Grosser } 854aaabbbf8STobias Grosser isl_set_free(ZeroSet); 855aaabbbf8STobias Grosser 856aaabbbf8STobias Grosser isl_ast_expr *Result = 857aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 858aaabbbf8STobias Grosser 859aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 860aaabbbf8STobias Grosser if (i > 0) { 861aaabbbf8STobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 862aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 863aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 864aaabbbf8STobias Grosser } 865aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 866aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 867aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 868aaabbbf8STobias Grosser } 869aaabbbf8STobias Grosser 870aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 871aaabbbf8STobias Grosser isl_set_free(Min); 872aaabbbf8STobias Grosser isl_ast_build_free(Build); 873aaabbbf8STobias Grosser 874aaabbbf8STobias Grosser return ResultValue; 875aaabbbf8STobias Grosser } 876aaabbbf8STobias Grosser 877abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 878abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 879abed4969SSiddharth Bhat 880abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 881abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 882abed4969SSiddharth Bhat "with managed memory"); 883abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 884abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 885abed4969SSiddharth Bhat return it->second; 886abed4969SSiddharth Bhat } else { 887abed4969SSiddharth Bhat Value *HostPtr; 888abed4969SSiddharth Bhat 889abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 890abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 891abed4969SSiddharth Bhat else 892abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 893abed4969SSiddharth Bhat 894abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 895abed4969SSiddharth Bhat if (Offset) { 896abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 897abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 898abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 899abed4969SSiddharth Bhat } 900abed4969SSiddharth Bhat 901abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 902abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 903abed4969SSiddharth Bhat return HostPtr; 904abed4969SSiddharth Bhat } 905abed4969SSiddharth Bhat } 906abed4969SSiddharth Bhat 90713c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 90813c78e4dSTobias Grosser enum DataDirection Direction) { 909abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 91013c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 91113c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 91213c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 91313c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 91413c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 91513c78e4dSTobias Grosser 91613c78e4dSTobias Grosser Value *Size = getArraySize(Array); 917aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 91813c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 91913c78e4dSTobias Grosser 920b06ff457STobias Grosser Value *HostPtr; 921b06ff457STobias Grosser 922b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 923b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 924b06ff457STobias Grosser else 925b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 92613c78e4dSTobias Grosser 927aaabbbf8STobias Grosser if (Offset) { 928aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 929aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 930aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 931aaabbbf8STobias Grosser } 932aaabbbf8STobias Grosser 93313c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 93413c78e4dSTobias Grosser 935aaabbbf8STobias Grosser if (Offset) { 936aaabbbf8STobias Grosser Size = Builder.CreateSub( 937ff40087aSTobias Grosser Size, Builder.CreateMul( 938ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 939aaabbbf8STobias Grosser } 940aaabbbf8STobias Grosser 94113c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 94213c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 94313c78e4dSTobias Grosser else 94413c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 94513c78e4dSTobias Grosser 94613c78e4dSTobias Grosser isl_id_free(Id); 94713c78e4dSTobias Grosser isl_ast_expr_free(Arg); 94813c78e4dSTobias Grosser isl_ast_expr_free(Expr); 94913c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 95013c78e4dSTobias Grosser } 95113c78e4dSTobias Grosser 9521fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 95332837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 95432837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 95532837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 95632837fe3STobias Grosser isl_id_free(Id); 95732837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 95832837fe3STobias Grosser 95932837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 96032837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 96132837fe3STobias Grosser createKernel(UserStmt); 96232837fe3STobias Grosser isl_ast_expr_free(Expr); 96332837fe3STobias Grosser return; 96432837fe3STobias Grosser } 96532837fe3STobias Grosser 96613c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 967abed4969SSiddharth Bhat if (!ManagedMemory) 96813c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 969abed4969SSiddharth Bhat else 970abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 971abed4969SSiddharth Bhat 97232837fe3STobias Grosser isl_ast_expr_free(Expr); 97313c78e4dSTobias Grosser return; 97413c78e4dSTobias Grosser } 97513c78e4dSTobias Grosser 97613c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 977abed4969SSiddharth Bhat if (!ManagedMemory) { 97813c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 979abed4969SSiddharth Bhat } else { 980abed4969SSiddharth Bhat createCallSynchronizeDevice(); 981abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 982abed4969SSiddharth Bhat } 98313c78e4dSTobias Grosser isl_ast_expr_free(Expr); 98438fc0aedSTobias Grosser return; 98538fc0aedSTobias Grosser } 98638fc0aedSTobias Grosser 9875260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 9885260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 9895260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 9905260c041STobias Grosser isl_id_free(Anno); 9915260c041STobias Grosser 9925260c041STobias Grosser switch (KernelStmt->type) { 9935260c041STobias Grosser case ppcg_kernel_domain: 994edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 9955260c041STobias Grosser isl_ast_node_free(UserStmt); 9965260c041STobias Grosser return; 9975260c041STobias Grosser case ppcg_kernel_copy: 998b513b491STobias Grosser createKernelCopy(KernelStmt); 9995260c041STobias Grosser isl_ast_expr_free(Expr); 10005260c041STobias Grosser isl_ast_node_free(UserStmt); 10015260c041STobias Grosser return; 10025260c041STobias Grosser case ppcg_kernel_sync: 10035260c041STobias Grosser createKernelSync(); 10045260c041STobias Grosser isl_ast_expr_free(Expr); 10055260c041STobias Grosser isl_ast_node_free(UserStmt); 10065260c041STobias Grosser return; 10075260c041STobias Grosser } 10085260c041STobias Grosser 10095260c041STobias Grosser isl_ast_expr_free(Expr); 10105260c041STobias Grosser isl_ast_node_free(UserStmt); 10115260c041STobias Grosser return; 10125260c041STobias Grosser } 1013b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1014b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1015b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1016b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1017b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1018b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1019b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1020b513b491STobias Grosser 1021b513b491STobias Grosser if (KernelStmt->u.c.read) { 1022b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1023b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1024b513b491STobias Grosser } else { 1025b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1026b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1027b513b491STobias Grosser } 1028b513b491STobias Grosser } 10295260c041STobias Grosser 1030edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1031edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1032edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1033edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1034edb885cbSTobias Grosser 1035edb885cbSTobias Grosser LoopToScevMapT LTS; 1036edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1037edb885cbSTobias Grosser 1038edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1039edb885cbSTobias Grosser 1040edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1041edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1042edb885cbSTobias Grosser else 1043a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1044edb885cbSTobias Grosser } 1045edb885cbSTobias Grosser 10465260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 10475260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1048*17f01968SSiddharth Bhat 1049*17f01968SSiddharth Bhat Function *Sync; 1050*17f01968SSiddharth Bhat 1051*17f01968SSiddharth Bhat switch (Arch) { 1052*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 1053*17f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 1054*17f01968SSiddharth Bhat break; 1055*17f01968SSiddharth Bhat } 1056*17f01968SSiddharth Bhat 10575260c041STobias Grosser Builder.CreateCall(Sync, {}); 10585260c041STobias Grosser } 10595260c041STobias Grosser 1060edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1061edb885cbSTobias Grosser /// 1062edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1063edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1064edb885cbSTobias Grosser /// 1065edb885cbSTobias Grosser /// @param Node The node to collect references for. 1066edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1067edb885cbSTobias Grosser /// 1068edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1069edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1070edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1071edb885cbSTobias Grosser return isl_bool_true; 1072edb885cbSTobias Grosser 1073edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1074edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1075edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1076edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1077edb885cbSTobias Grosser isl_id_free(Id); 1078edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1079edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1080edb885cbSTobias Grosser 1081edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1082edb885cbSTobias Grosser return isl_bool_true; 1083edb885cbSTobias Grosser 1084edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1085edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1086edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1087edb885cbSTobias Grosser isl_id_free(Id); 1088edb885cbSTobias Grosser 108900bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1090edb885cbSTobias Grosser 1091edb885cbSTobias Grosser return isl_bool_true; 1092edb885cbSTobias Grosser } 1093edb885cbSTobias Grosser 1094edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1095edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1096edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1097edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1098edb885cbSTobias Grosser SubtreeReferences References = { 1099edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1100edb885cbSTobias Grosser 1101edb885cbSTobias Grosser for (const auto &I : IDToValue) 1102edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1103edb885cbSTobias Grosser 1104edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1105edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1106edb885cbSTobias Grosser 1107edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1108edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1109edb885cbSTobias Grosser 1110edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1111d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1112edb885cbSTobias Grosser 1113edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1114edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1115edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1116edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1117edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1118edb885cbSTobias Grosser SubtreeValues.remove(Val); 1119edb885cbSTobias Grosser isl_id_free(Id); 1120edb885cbSTobias Grosser } 1121edb885cbSTobias Grosser isl_space_free(Space); 1122edb885cbSTobias Grosser 1123edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1124edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1125edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1126edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1127edb885cbSTobias Grosser SubtreeValues.remove(Val); 1128edb885cbSTobias Grosser isl_id_free(Id); 1129edb885cbSTobias Grosser } 1130edb885cbSTobias Grosser 1131edb885cbSTobias Grosser return SubtreeValues; 1132edb885cbSTobias Grosser } 1133edb885cbSTobias Grosser 113474dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 113574dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 113674dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 113774dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 113874dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 113974dc3cb4STobias Grosser 114074dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 114174dc3cb4STobias Grosser DT.eraseNode(BB); 114274dc3cb4STobias Grosser } 114374dc3cb4STobias Grosser 114474dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 114574dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 114674dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 114774dc3cb4STobias Grosser if (L) 114874dc3cb4STobias Grosser SE.forgetLoop(L); 114974dc3cb4STobias Grosser } 115074dc3cb4STobias Grosser } 115174dc3cb4STobias Grosser 115274dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 115374dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 115474dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 115574dc3cb4STobias Grosser if (L) 115674dc3cb4STobias Grosser SE.forgetLoop(L); 115774dc3cb4STobias Grosser LI.removeBlock(&BB); 115874dc3cb4STobias Grosser } 115974dc3cb4STobias Grosser } 116074dc3cb4STobias Grosser 116179a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 116279a947c2STobias Grosser std::vector<Value *> Sizes; 116379a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 116479a947c2STobias Grosser 116579a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 116679a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 116779a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 116879a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 116979a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 117079a947c2STobias Grosser Sizes.push_back(Res); 117179a947c2STobias Grosser } 117279a947c2STobias Grosser isl_ast_build_free(Context); 117379a947c2STobias Grosser 117479a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 117579a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 117679a947c2STobias Grosser 117779a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 117879a947c2STobias Grosser } 117979a947c2STobias Grosser 118079a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 118179a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 118279a947c2STobias Grosser std::vector<Value *> Sizes; 118379a947c2STobias Grosser 118479a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 118579a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 118679a947c2STobias Grosser Sizes.push_back(Res); 118779a947c2STobias Grosser } 118879a947c2STobias Grosser 118979a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 119079a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 119179a947c2STobias Grosser 119279a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 119379a947c2STobias Grosser } 119479a947c2STobias Grosser 119557693272STobias Grosser Value * 119657693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 119757693272STobias Grosser SetVector<Value *> SubtreeValues) { 11984e18d71cSTobias Grosser Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 11994e18d71cSTobias Grosser std::distance(F->arg_begin(), F->arg_end())); 120079a947c2STobias Grosser 120179a947c2STobias Grosser BasicBlock *EntryBlock = 120279a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 120367726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 120479a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 120567726b32STobias Grosser Instruction *Parameters = new AllocaInst( 120667726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 120779a947c2STobias Grosser 120879a947c2STobias Grosser int Index = 0; 120979a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 121079a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 121179a947c2STobias Grosser continue; 121279a947c2STobias Grosser 121379a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 121479a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 121579a947c2STobias Grosser 1216abed4969SSiddharth Bhat Value *DevArray = nullptr; 1217abed4969SSiddharth Bhat if (ManagedMemory) { 1218abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1219abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1220abed4969SSiddharth Bhat } else { 1221abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 122279a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1223abed4969SSiddharth Bhat } 1224abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1225abed4969SSiddharth Bhat "initialized"); 1226aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1227aaabbbf8STobias Grosser 1228aaabbbf8STobias Grosser if (Offset) { 1229aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1230aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1231aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1232aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1233aaabbbf8STobias Grosser } 1234fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1235fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1236aaabbbf8STobias Grosser 1237fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1238abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1239abed4969SSiddharth Bhat if (ManagedMemory) 1240abed4969SSiddharth Bhat ValPtr = DevArray; 1241abed4969SSiddharth Bhat else 1242abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1243abed4969SSiddharth Bhat 1244abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1245abed4969SSiddharth Bhat " to be stored into Parameters"); 1246fe74a7a1STobias Grosser Value *ValPtrCast = 1247fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1248fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1249fe74a7a1STobias Grosser } else { 125067726b32STobias Grosser Instruction *Param = 125167726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 125267726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 125379a947c2STobias Grosser EntryBlock->getTerminator()); 125479a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 125579a947c2STobias Grosser Value *ParamTyped = 125679a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 125779a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1258fe74a7a1STobias Grosser } 125979a947c2STobias Grosser Index++; 126079a947c2STobias Grosser } 126179a947c2STobias Grosser 1262a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1263a490147cSTobias Grosser 1264a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1265a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1266a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1267a490147cSTobias Grosser isl_id_free(Id); 126867726b32STobias Grosser Instruction *Param = 126967726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 127067726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1271a490147cSTobias Grosser EntryBlock->getTerminator()); 1272a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1273a490147cSTobias Grosser Value *Slot = Builder.CreateGEP( 1274a490147cSTobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1275a490147cSTobias Grosser Value *ParamTyped = 1276a490147cSTobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1277a490147cSTobias Grosser Builder.CreateStore(ParamTyped, Slot); 1278a490147cSTobias Grosser Index++; 1279a490147cSTobias Grosser } 1280a490147cSTobias Grosser 1281d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1282d8b94bcaSTobias Grosser 1283d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1284d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1285d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1286d8b94bcaSTobias Grosser isl_id_free(Id); 128767726b32STobias Grosser Instruction *Param = 128867726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 128967726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1290d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1291d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1292d8b94bcaSTobias Grosser Value *Slot = Builder.CreateGEP( 1293d8b94bcaSTobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1294d8b94bcaSTobias Grosser Value *ParamTyped = 1295d8b94bcaSTobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1296d8b94bcaSTobias Grosser Builder.CreateStore(ParamTyped, Slot); 1297d8b94bcaSTobias Grosser Index++; 1298d8b94bcaSTobias Grosser } 1299d8b94bcaSTobias Grosser 130057693272STobias Grosser for (auto Val : SubtreeValues) { 130167726b32STobias Grosser Instruction *Param = 130267726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 130367726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 130457693272STobias Grosser EntryBlock->getTerminator()); 130557693272STobias Grosser Builder.CreateStore(Val, Param); 130657693272STobias Grosser Value *Slot = Builder.CreateGEP( 130757693272STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 130857693272STobias Grosser Value *ParamTyped = 130957693272STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 131057693272STobias Grosser Builder.CreateStore(ParamTyped, Slot); 131157693272STobias Grosser Index++; 131257693272STobias Grosser } 131357693272STobias Grosser 131479a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 131579a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 131679a947c2STobias Grosser Launch + "_params_i8ptr", Location); 131779a947c2STobias Grosser } 131879a947c2STobias Grosser 131932837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 132032837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 132132837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 132232837fe3STobias Grosser isl_id_free(Id); 132332837fe3STobias Grosser isl_ast_node_free(KernelStmt); 132432837fe3STobias Grosser 1325bc653f20STobias Grosser if (Kernel->n_grid > 1) 1326bc653f20STobias Grosser DeepestParallel = 1327bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1328bc653f20STobias Grosser else 1329bc653f20STobias Grosser DeepestSequential = 1330bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1331bc653f20STobias Grosser 1332c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1333c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1334c1c6a2a6STobias Grosser 1335edb885cbSTobias Grosser SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel); 1336edb885cbSTobias Grosser 133732837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 133832837fe3STobias Grosser 133932837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1340472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1341edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1342587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1343b06ff457STobias Grosser ScalarMap.clear(); 134432837fe3STobias Grosser 1345edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1346edb885cbSTobias Grosser 1347edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1348edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1349edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1350edb885cbSTobias Grosser for (const Loop *L : Loops) { 1351edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1352edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1353edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1354edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1355edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1356edb885cbSTobias Grosser SubtreeValues.insert(V); 1357edb885cbSTobias Grosser } 1358edb885cbSTobias Grosser 1359edb885cbSTobias Grosser createKernelFunction(Kernel, SubtreeValues); 136032837fe3STobias Grosser 136159ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 136259ab0705STobias Grosser 136351dfc275STobias Grosser finalizeKernelArguments(Kernel); 136474dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 1365c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 136674dc3cb4STobias Grosser clearDominators(F); 136774dc3cb4STobias Grosser clearScalarEvolution(F); 136874dc3cb4STobias Grosser clearLoops(F); 136974dc3cb4STobias Grosser 1370472f9654STobias Grosser IDToValue = HostIDs; 137132837fe3STobias Grosser 1372b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1373b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1374edb885cbSTobias Grosser EscapeMap.clear(); 1375edb885cbSTobias Grosser IDToSAI.clear(); 137674dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 137774dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 13784d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 137974dc3cb4STobias Grosser LocalArrays.clear(); 1380edb885cbSTobias Grosser 138151dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 138251dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 138357693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 138479a947c2STobias Grosser 138557793596STobias Grosser std::string Name = "kernel_" + std::to_string(Kernel->id); 138657793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 138757793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 138857793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 138979a947c2STobias Grosser 139079a947c2STobias Grosser Value *GridDimX, *GridDimY; 139179a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 139279a947c2STobias Grosser 139379a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 139479a947c2STobias Grosser BlockDimZ, Parameters); 139557793596STobias Grosser createCallFreeKernel(GPUKernel); 1396b513b491STobias Grosser 1397b513b491STobias Grosser for (auto Id : KernelIds) 1398b513b491STobias Grosser isl_id_free(Id); 1399b513b491STobias Grosser 1400b513b491STobias Grosser KernelIds.clear(); 140132837fe3STobias Grosser } 140232837fe3STobias Grosser 140332837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 140432837fe3STobias Grosser /// 140532837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 140632837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1407d277fedaSSiddharth Bhat std::string Ret = ""; 140832837fe3STobias Grosser 1409d277fedaSSiddharth Bhat if (!is64Bit) { 1410d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1411d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1412d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1413d277fedaSSiddharth Bhat } else { 1414d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1415d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1416d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1417d277fedaSSiddharth Bhat } 141832837fe3STobias Grosser 141932837fe3STobias Grosser return Ret; 142032837fe3STobias Grosser } 142132837fe3STobias Grosser 1422edb885cbSTobias Grosser Function * 1423edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1424edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 142532837fe3STobias Grosser std::vector<Type *> Args; 142632837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 142732837fe3STobias Grosser 142832837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 142932837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 143032837fe3STobias Grosser continue; 143132837fe3STobias Grosser 1432fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1433fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1434fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1435fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 1436fe74a7a1STobias Grosser } else { 1437d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1438d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 143932837fe3STobias Grosser } 1440fe74a7a1STobias Grosser } 144132837fe3STobias Grosser 1442f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1443f6044bd0STobias Grosser 1444f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 1445f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 1446f6044bd0STobias Grosser 1447c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1448c84a1995STobias Grosser 1449cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1450cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1451cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1452cf66ef26STobias Grosser isl_id_free(Id); 1453cf66ef26STobias Grosser Args.push_back(Val->getType()); 1454cf66ef26STobias Grosser } 1455c84a1995STobias Grosser 1456edb885cbSTobias Grosser for (auto *V : SubtreeValues) 1457edb885cbSTobias Grosser Args.push_back(V->getType()); 1458edb885cbSTobias Grosser 145932837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 146032837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 146132837fe3STobias Grosser GPUModule.get()); 1462*17f01968SSiddharth Bhat 1463*17f01968SSiddharth Bhat switch (Arch) { 1464*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 146532837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 1466*17f01968SSiddharth Bhat break; 1467*17f01968SSiddharth Bhat } 146832837fe3STobias Grosser 146932837fe3STobias Grosser auto Arg = FN->arg_begin(); 147032837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 147132837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 147232837fe3STobias Grosser continue; 147332837fe3STobias Grosser 1474edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1475edb885cbSTobias Grosser 1476edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1477edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1478edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1479edb885cbSTobias Grosser Value *Val = &*Arg; 1480edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1481edb885cbSTobias Grosser isl_ast_build *Build = 1482edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1483f5aff704SRoman Gareev Sizes.push_back(nullptr); 1484edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1485edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1486edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1487edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1488edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1489edb885cbSTobias Grosser } 1490edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 14914d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 149274dc3cb4STobias Grosser LocalArrays.push_back(Val); 1493edb885cbSTobias Grosser 1494edb885cbSTobias Grosser isl_ast_build_free(Build); 1495b513b491STobias Grosser KernelIds.push_back(Id); 1496edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 149732837fe3STobias Grosser Arg++; 149832837fe3STobias Grosser } 149932837fe3STobias Grosser 1500f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1501f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1502f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1503f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1504f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1505f6044bd0STobias Grosser Arg++; 1506f6044bd0STobias Grosser } 1507f6044bd0STobias Grosser 1508c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1509c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1510c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 151112453403STobias Grosser Value *Val = IDToValue[Id]; 151212453403STobias Grosser ValueMap[Val] = &*Arg; 1513c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1514c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1515c84a1995STobias Grosser Arg++; 1516c84a1995STobias Grosser } 1517c84a1995STobias Grosser 1518edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1519edb885cbSTobias Grosser Arg->setName(V->getName()); 1520edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1521edb885cbSTobias Grosser Arg++; 1522edb885cbSTobias Grosser } 1523edb885cbSTobias Grosser 152432837fe3STobias Grosser return FN; 152532837fe3STobias Grosser } 152632837fe3STobias Grosser 1527472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1528*17f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 1529*17f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1530472f9654STobias Grosser 1531*17f01968SSiddharth Bhat switch (Arch) { 1532*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 1533*17f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 1534*17f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 1535*17f01968SSiddharth Bhat 1536*17f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 1537*17f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 1538*17f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 1539*17f01968SSiddharth Bhat break; 1540*17f01968SSiddharth Bhat } 1541472f9654STobias Grosser 1542472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1543472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1544472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1545472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1546472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1547472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1548472f9654STobias Grosser IDToValue[Id] = Val; 1549472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1550472f9654STobias Grosser }; 1551472f9654STobias Grosser 1552472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1553472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1554472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1555472f9654STobias Grosser } 1556472f9654STobias Grosser 1557472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1558472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1559472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1560472f9654STobias Grosser } 1561472f9654STobias Grosser } 1562472f9654STobias Grosser 156300bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 156400bb5a99STobias Grosser auto Arg = FN->arg_begin(); 156500bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 156600bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 156700bb5a99STobias Grosser continue; 156800bb5a99STobias Grosser 156900bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 157000bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 157100bb5a99STobias Grosser isl_id_free(Id); 157200bb5a99STobias Grosser 157300bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 157400bb5a99STobias Grosser Arg++; 157500bb5a99STobias Grosser continue; 157600bb5a99STobias Grosser } 157700bb5a99STobias Grosser 1578fe74a7a1STobias Grosser Value *Val = &*Arg; 1579fe74a7a1STobias Grosser 1580fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 158100bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 1582fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1583fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 1584fe74a7a1STobias Grosser } 1585fe74a7a1STobias Grosser 1586fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 158700bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 158800bb5a99STobias Grosser 158900bb5a99STobias Grosser Arg++; 159000bb5a99STobias Grosser } 159100bb5a99STobias Grosser } 159200bb5a99STobias Grosser 159351dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 159451dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 159551dfc275STobias Grosser auto Arg = FN->arg_begin(); 159651dfc275STobias Grosser 159751dfc275STobias Grosser bool StoredScalar = false; 159851dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 159951dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 160051dfc275STobias Grosser continue; 160151dfc275STobias Grosser 160251dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 160351dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 160451dfc275STobias Grosser isl_id_free(Id); 160551dfc275STobias Grosser 160651dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 160751dfc275STobias Grosser Arg++; 160851dfc275STobias Grosser continue; 160951dfc275STobias Grosser } 161051dfc275STobias Grosser 161151dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 161251dfc275STobias Grosser Arg++; 161351dfc275STobias Grosser continue; 161451dfc275STobias Grosser } 161551dfc275STobias Grosser 161651dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 161751dfc275STobias Grosser Value *ArgPtr = &*Arg; 161851dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 161951dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 162051dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 162151dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 162251dfc275STobias Grosser StoredScalar = true; 162351dfc275STobias Grosser 162451dfc275STobias Grosser Arg++; 162551dfc275STobias Grosser } 162651dfc275STobias Grosser 162751dfc275STobias Grosser if (StoredScalar) 162851dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 162951dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 163051dfc275STobias Grosser /// To support this case we need to store these scalars back at each 163151dfc275STobias Grosser /// memory store or at least before each kernel barrier. 163251dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 163351dfc275STobias Grosser BuildSuccessful = 0; 163451dfc275STobias Grosser } 163551dfc275STobias Grosser 1636b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1637b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1638b513b491STobias Grosser 1639b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 1640b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 1641b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1642b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1643b513b491STobias Grosser 1644f919d8b3STobias Grosser Type *ArrayTy = EleTy; 1645b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 1646b513b491STobias Grosser 1647f5aff704SRoman Gareev Sizes.push_back(nullptr); 1648928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1649b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1650f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 1651b513b491STobias Grosser isl_val_free(Val); 1652b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1653928d7573STobias Grosser } 1654928d7573STobias Grosser 1655928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 1656928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1657928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 1658928d7573STobias Grosser isl_val_free(Val); 1659b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 1660b513b491STobias Grosser } 1661b513b491STobias Grosser 1662130ca30fSTobias Grosser const ScopArrayInfo *SAI; 1663130ca30fSTobias Grosser Value *Allocation; 1664130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 1665130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 1666130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1667130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1668130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1669f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1670f919d8b3STobias Grosser 1671130ca30fSTobias Grosser Allocation = GlobalVar; 1672130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 1673130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1674130ca30fSTobias Grosser } else { 1675130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 1676130ca30fSTobias Grosser } 16774d5a9172STobias Grosser SAI = 16784d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1679b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1680130ca30fSTobias Grosser IDToValue[Id] = Allocation; 1681130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 1682b513b491STobias Grosser KernelIds.push_back(Id); 1683b513b491STobias Grosser IDToSAI[Id] = SAI; 1684b513b491STobias Grosser } 1685b513b491STobias Grosser } 1686b513b491STobias Grosser 1687edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel, 1688edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 168932837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 169032837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 1691*17f01968SSiddharth Bhat 1692*17f01968SSiddharth Bhat switch (Arch) { 1693*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 1694*17f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 169532837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 1696*17f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 1697*17f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 169832837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 1699*17f01968SSiddharth Bhat break; 1700*17f01968SSiddharth Bhat } 170132837fe3STobias Grosser 1702edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 170332837fe3STobias Grosser 170459ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 170532837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 170632837fe3STobias Grosser 170759ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 170859ab0705STobias Grosser 170932837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 171032837fe3STobias Grosser Builder.CreateRetVoid(); 171132837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1712472f9654STobias Grosser 1713629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 1714629109b6STobias Grosser 171500bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 1716b513b491STobias Grosser createKernelVariables(Kernel, FN); 1717472f9654STobias Grosser insertKernelIntrinsics(Kernel); 171832837fe3STobias Grosser } 171932837fe3STobias Grosser 172074dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 1721*17f01968SSiddharth Bhat llvm::Triple GPUTriple; 1722*17f01968SSiddharth Bhat 1723*17f01968SSiddharth Bhat switch (Arch) { 1724*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 1725*17f01968SSiddharth Bhat switch (Runtime) { 1726*17f01968SSiddharth Bhat case GPURuntime::CUDA: 1727*17f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 1728*17f01968SSiddharth Bhat break; 1729*17f01968SSiddharth Bhat case GPURuntime::OpenCL: 1730*17f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 1731*17f01968SSiddharth Bhat break; 1732*17f01968SSiddharth Bhat } 1733*17f01968SSiddharth Bhat break; 1734*17f01968SSiddharth Bhat } 1735*17f01968SSiddharth Bhat 173674dc3cb4STobias Grosser std::string ErrMsg; 173774dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 173874dc3cb4STobias Grosser 173974dc3cb4STobias Grosser if (!GPUTarget) { 174074dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 174174dc3cb4STobias Grosser return ""; 174274dc3cb4STobias Grosser } 174374dc3cb4STobias Grosser 174474dc3cb4STobias Grosser TargetOptions Options; 174574dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 1746*17f01968SSiddharth Bhat 1747*17f01968SSiddharth Bhat std::string subtarget; 1748*17f01968SSiddharth Bhat 1749*17f01968SSiddharth Bhat switch (Arch) { 1750*17f01968SSiddharth Bhat case GPUArch::NVPTX64: 1751*17f01968SSiddharth Bhat subtarget = CudaVersion; 1752*17f01968SSiddharth Bhat break; 1753*17f01968SSiddharth Bhat } 1754*17f01968SSiddharth Bhat 1755*17f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 1756*17f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 175774dc3cb4STobias Grosser 175874dc3cb4STobias Grosser SmallString<0> ASMString; 175974dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 176074dc3cb4STobias Grosser llvm::legacy::PassManager PM; 176174dc3cb4STobias Grosser 176274dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 176374dc3cb4STobias Grosser 176474dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 176574dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 176674dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 176774dc3cb4STobias Grosser return ""; 176874dc3cb4STobias Grosser } 176974dc3cb4STobias Grosser 177074dc3cb4STobias Grosser PM.run(*GPUModule); 177174dc3cb4STobias Grosser 177274dc3cb4STobias Grosser return ASMStream.str(); 177374dc3cb4STobias Grosser } 177474dc3cb4STobias Grosser 177557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 17765857b701STobias Grosser if (verifyModule(*GPUModule)) { 17775857b701STobias Grosser BuildSuccessful = false; 17785857b701STobias Grosser return ""; 17795857b701STobias Grosser } 178032837fe3STobias Grosser 178132837fe3STobias Grosser if (DumpKernelIR) 178232837fe3STobias Grosser outs() << *GPUModule << "\n"; 178332837fe3STobias Grosser 17849a18d559STobias Grosser // Optimize module. 17859a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 17869a18d559STobias Grosser PassManagerBuilder PassBuilder; 17879a18d559STobias Grosser PassBuilder.OptLevel = 3; 17889a18d559STobias Grosser PassBuilder.SizeLevel = 0; 17899a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 17909a18d559STobias Grosser OptPasses.run(*GPUModule); 17919a18d559STobias Grosser 179274dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 179374dc3cb4STobias Grosser 179474dc3cb4STobias Grosser if (DumpKernelASM) 179574dc3cb4STobias Grosser outs() << Assembly << "\n"; 179674dc3cb4STobias Grosser 179732837fe3STobias Grosser GPUModule.release(); 1798472f9654STobias Grosser KernelIDs.clear(); 179957793596STobias Grosser 180057793596STobias Grosser return Assembly; 180132837fe3STobias Grosser } 180232837fe3STobias Grosser 18039dfe4e7cSTobias Grosser namespace { 18049dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 18059dfe4e7cSTobias Grosser public: 18069dfe4e7cSTobias Grosser static char ID; 18079dfe4e7cSTobias Grosser 1808*17f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 1809*17f01968SSiddharth Bhat 1810*17f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 1811*17f01968SSiddharth Bhat 1812e938517eSTobias Grosser /// The scop that is currently processed. 1813e938517eSTobias Grosser Scop *S; 1814e938517eSTobias Grosser 181538fc0aedSTobias Grosser LoopInfo *LI; 181638fc0aedSTobias Grosser DominatorTree *DT; 181738fc0aedSTobias Grosser ScalarEvolution *SE; 181838fc0aedSTobias Grosser const DataLayout *DL; 181938fc0aedSTobias Grosser RegionInfo *RI; 182038fc0aedSTobias Grosser 18219dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 18229dfe4e7cSTobias Grosser 1823e938517eSTobias Grosser /// Construct compilation options for PPCG. 1824e938517eSTobias Grosser /// 1825e938517eSTobias Grosser /// @returns The compilation options. 1826e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 1827e938517eSTobias Grosser auto DebugOptions = 1828e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 1829e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 1830e938517eSTobias Grosser 1831e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 1832e938517eSTobias Grosser DebugOptions->dump_schedule = false; 1833e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 1834e938517eSTobias Grosser DebugOptions->dump_sizes = false; 18358950ceadSTobias Grosser DebugOptions->verbose = false; 1836e938517eSTobias Grosser 1837e938517eSTobias Grosser Options->debug = DebugOptions; 1838e938517eSTobias Grosser 1839e938517eSTobias Grosser Options->reschedule = true; 1840e938517eSTobias Grosser Options->scale_tile_loops = false; 1841e938517eSTobias Grosser Options->wrap = false; 1842e938517eSTobias Grosser 1843e938517eSTobias Grosser Options->non_negative_parameters = false; 1844e938517eSTobias Grosser Options->ctx = nullptr; 1845e938517eSTobias Grosser Options->sizes = nullptr; 1846e938517eSTobias Grosser 18474eaedde5STobias Grosser Options->tile_size = 32; 18484eaedde5STobias Grosser 1849130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 1850b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 1851b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 1852e938517eSTobias Grosser 1853e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 1854e938517eSTobias Grosser Options->openmp = false; 1855e938517eSTobias Grosser Options->linearize_device_arrays = true; 1856e938517eSTobias Grosser Options->live_range_reordering = false; 1857e938517eSTobias Grosser 1858e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 1859e938517eSTobias Grosser Options->opencl_use_gpu = false; 1860e938517eSTobias Grosser Options->opencl_n_include_file = 0; 1861e938517eSTobias Grosser Options->opencl_include_files = nullptr; 1862e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 1863e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 1864e938517eSTobias Grosser 1865e938517eSTobias Grosser Options->save_schedule_file = nullptr; 1866e938517eSTobias Grosser Options->load_schedule_file = nullptr; 1867e938517eSTobias Grosser 1868e938517eSTobias Grosser return Options; 1869e938517eSTobias Grosser } 1870e938517eSTobias Grosser 1871f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 1872f384594dSTobias Grosser /// 1873f384594dSTobias Grosser /// Instead of a normal access of the form: 1874f384594dSTobias Grosser /// 1875f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 1876f384594dSTobias Grosser /// 1877f384594dSTobias Grosser /// a tagged access has the form 1878f384594dSTobias Grosser /// 1879f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 1880f384594dSTobias Grosser /// 1881f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 1882f384594dSTobias Grosser /// triggered the access. 1883f384594dSTobias Grosser /// 1884f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 1885f384594dSTobias Grosser /// 1886f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 1887f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 1888f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 1889f384594dSTobias Grosser 1890f384594dSTobias Grosser for (auto &Stmt : *S) 1891f384594dSTobias Grosser for (auto &Acc : Stmt) 1892f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 1893f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 1894f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 1895f384594dSTobias Grosser 1896f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 1897f384594dSTobias Grosser Space = isl_space_range(Space); 1898f384594dSTobias Grosser Space = isl_space_from_range(Space); 18996293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 1900f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 1901f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 1902f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 1903f384594dSTobias Grosser } 1904f384594dSTobias Grosser 1905f384594dSTobias Grosser return Accesses; 1906f384594dSTobias Grosser } 1907f384594dSTobias Grosser 1908f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 1909f384594dSTobias Grosser /// 1910f384594dSTobias Grosser /// @see getTaggedAccesses 1911f384594dSTobias Grosser isl_union_map *getTaggedReads() { 1912f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 1913f384594dSTobias Grosser } 1914f384594dSTobias Grosser 1915f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 1916f384594dSTobias Grosser /// 1917f384594dSTobias Grosser /// @see getTaggedAccesses 1918f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 1919f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 1920f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 1921f384594dSTobias Grosser } 1922f384594dSTobias Grosser 1923f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 1924f384594dSTobias Grosser /// 1925f384594dSTobias Grosser /// @see getTaggedAccesses 1926f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 1927f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 1928f384594dSTobias Grosser } 1929f384594dSTobias Grosser 1930aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 1931aef5196fSTobias Grosser /// 1932aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 1933aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 1934aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 1935aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 1936aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 1937aef5196fSTobias Grosser /// the data format that ppcg expects. 1938aef5196fSTobias Grosser /// 1939aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 1940aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 1941aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 1942bd81a7eeSTobias Grosser S->getIslCtx(), 1943bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 1944aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 1945aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 1946aef5196fSTobias Grosser 1947aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 1948aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 1949aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1950aef5196fSTobias Grosser } 1951aef5196fSTobias Grosser 1952aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 1953d7754a12SRoman Gareev auto Id = Array->getBasePtrId(); 1954aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1955aef5196fSTobias Grosser } 1956aef5196fSTobias Grosser 1957aef5196fSTobias Grosser isl_space_free(Space); 1958aef5196fSTobias Grosser isl_ast_expr_free(Zero); 1959aef5196fSTobias Grosser 1960aef5196fSTobias Grosser return Names; 1961aef5196fSTobias Grosser } 1962aef5196fSTobias Grosser 1963e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 1964e938517eSTobias Grosser /// 1965f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 1966f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 1967f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 1968f384594dSTobias Grosser /// the PPCG default behaviour more closely. 1969e938517eSTobias Grosser /// 1970e938517eSTobias Grosser /// @returns A new ppcg scop. 1971e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 1972e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 1973e938517eSTobias Grosser 1974e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 1975e938517eSTobias Grosser 1976e938517eSTobias Grosser PPCGScop->start = 0; 1977e938517eSTobias Grosser PPCGScop->end = 0; 1978e938517eSTobias Grosser 1979f384594dSTobias Grosser PPCGScop->context = S->getContext(); 1980f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 1981e938517eSTobias Grosser PPCGScop->call = nullptr; 1982f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 1983f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 1984e938517eSTobias Grosser PPCGScop->live_in = nullptr; 1985f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 1986f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 1987f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 1988f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 1989e938517eSTobias Grosser PPCGScop->live_out = nullptr; 1990f384594dSTobias Grosser PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace()); 1991e938517eSTobias Grosser PPCGScop->tagger = nullptr; 1992e938517eSTobias Grosser 1993e938517eSTobias Grosser PPCGScop->independence = nullptr; 1994e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 1995e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 1996e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 1997e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 1998e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 1999e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2000e938517eSTobias Grosser 2001f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2002aef5196fSTobias Grosser PPCGScop->names = getNames(); 2003e938517eSTobias Grosser 2004e938517eSTobias Grosser PPCGScop->pet = nullptr; 2005e938517eSTobias Grosser 2006f384594dSTobias Grosser compute_tagger(PPCGScop); 2007f384594dSTobias Grosser compute_dependences(PPCGScop); 2008f384594dSTobias Grosser 2009e938517eSTobias Grosser return PPCGScop; 2010e938517eSTobias Grosser } 2011e938517eSTobias Grosser 201260f63b49STobias Grosser /// Collect the array acesses in a statement. 201360f63b49STobias Grosser /// 201460f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 201560f63b49STobias Grosser /// 201660f63b49STobias Grosser /// @returns A list of array accesses. 201760f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 201860f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 201960f63b49STobias Grosser 202060f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 202160f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 202260f63b49STobias Grosser Access->read = Acc->isRead(); 202360f63b49STobias Grosser Access->write = Acc->isWrite(); 202460f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 202560f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 202660f63b49STobias Grosser Space = isl_space_range(Space); 202760f63b49STobias Grosser Space = isl_space_from_range(Space); 20286293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 202960f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 203060f63b49STobias Grosser Access->tagged_access = 203160f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2032b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 203360f63b49STobias Grosser Access->ref_id = Acc->getId(); 203460f63b49STobias Grosser Access->next = Accesses; 2035b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 203660f63b49STobias Grosser Accesses = Access; 203760f63b49STobias Grosser } 203860f63b49STobias Grosser 203960f63b49STobias Grosser return Accesses; 204060f63b49STobias Grosser } 204160f63b49STobias Grosser 204269b46751STobias Grosser /// Collect the list of GPU statements. 204369b46751STobias Grosser /// 204469b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 204569b46751STobias Grosser /// as well as a list with all memory accesses. 204669b46751STobias Grosser /// 204769b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 204869b46751STobias Grosser /// 204969b46751STobias Grosser /// @returns A linked-list of statements. 205069b46751STobias Grosser gpu_stmt *getStatements() { 205169b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 205269b46751STobias Grosser std::distance(S->begin(), S->end())); 205369b46751STobias Grosser 205469b46751STobias Grosser int i = 0; 205569b46751STobias Grosser for (auto &Stmt : *S) { 205669b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 205769b46751STobias Grosser 205869b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 205969b46751STobias Grosser 206069b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 206169b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 206260f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 206369b46751STobias Grosser i++; 206469b46751STobias Grosser } 206569b46751STobias Grosser 206669b46751STobias Grosser return Stmts; 206769b46751STobias Grosser } 206869b46751STobias Grosser 206960f63b49STobias Grosser /// Derive the extent of an array. 207060f63b49STobias Grosser /// 2071d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2072d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2073d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2074d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2075d58acf86STobias Grosser /// subscript value for the first dimension. 207660f63b49STobias Grosser /// 207760f63b49STobias Grosser /// @param Array The array to derive the extent for. 207860f63b49STobias Grosser /// 207960f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 208060f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2081d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 208260f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 208360f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2084d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 208560f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2086d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2087d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2088d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2089d58acf86STobias Grosser 2090d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2091d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2092d58acf86STobias Grosser return isl_set_empty(Array->getSpace()); 2093d58acf86STobias Grosser } 2094d58acf86STobias Grosser 2095d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2096d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2097d58acf86STobias Grosser return isl_set_universe(Array->getSpace()); 2098d58acf86STobias Grosser } 2099d58acf86STobias Grosser 210060f63b49STobias Grosser isl_set *AccessSet = 210160f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 210260f63b49STobias Grosser 2103d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2104d58acf86STobias Grosser isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2105d58acf86STobias Grosser 2106d58acf86STobias Grosser isl_pw_aff *Val = 2107d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2108d58acf86STobias Grosser 2109d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2110d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2111d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2112d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2113d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2114d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2115d58acf86STobias Grosser OuterMin = 2116d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2117d58acf86STobias Grosser OuterMax = 2118d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2119d58acf86STobias Grosser 2120d58acf86STobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace()); 2121d58acf86STobias Grosser 2122d58acf86STobias Grosser Extent = isl_set_intersect( 2123d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2124d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2125d58acf86STobias Grosser 2126d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2127d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2128d58acf86STobias Grosser 2129d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) { 2130d58acf86STobias Grosser isl_pw_aff *PwAff = 2131d58acf86STobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2132d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2133d58acf86STobias Grosser isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2134d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2135d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2136d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2137d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2138d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2139d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2140d58acf86STobias Grosser } 2141d58acf86STobias Grosser 2142d58acf86STobias Grosser return Extent; 214360f63b49STobias Grosser } 214460f63b49STobias Grosser 214560f63b49STobias Grosser /// Derive the bounds of an array. 214660f63b49STobias Grosser /// 214760f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 214860f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 214960f63b49STobias Grosser /// ScopArrayInfo. 215060f63b49STobias Grosser /// 215160f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 215260f63b49STobias Grosser /// @param Array The polly array from which to take the information. 215360f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 215460f63b49STobias Grosser if (PPCGArray.n_index > 0) { 215502293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 215602293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 215702293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 215802293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 215902293ed7STobias Grosser isl_set_free(Dom); 216002293ed7STobias Grosser isl_aff *Zero = isl_aff_zero_on_domain(LS); 216102293ed7STobias Grosser PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 216202293ed7STobias Grosser } else { 216360f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 216460f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 216560f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 216660f63b49STobias Grosser isl_set_free(Dom); 216760f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 216802293ed7STobias Grosser isl_local_space *LS = 216902293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 217060f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 217160f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 217260f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 217360f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 217460f63b49STobias Grosser PPCGArray.bound[0] = Bound; 217560f63b49STobias Grosser } 217602293ed7STobias Grosser } 217760f63b49STobias Grosser 217860f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 217960f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 218060f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 218160f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 218260f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 218360f63b49STobias Grosser PPCGArray.bound[i] = Bound; 218460f63b49STobias Grosser } 218560f63b49STobias Grosser } 218660f63b49STobias Grosser 218760f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 218860f63b49STobias Grosser /// 218960f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 219060f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 219160f63b49STobias Grosser int i = 0; 2192d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 219360f63b49STobias Grosser std::string TypeName; 219460f63b49STobias Grosser raw_string_ostream OS(TypeName); 219560f63b49STobias Grosser 219660f63b49STobias Grosser OS << *Array->getElementType(); 219760f63b49STobias Grosser TypeName = OS.str(); 219860f63b49STobias Grosser 219960f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 220060f63b49STobias Grosser 220160f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 220260f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 220360f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 220460f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 220560f63b49STobias Grosser PPCGArray.extent = nullptr; 220660f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 220760f63b49STobias Grosser PPCGArray.bound = 220860f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 220960f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 221060f63b49STobias Grosser PPCGArray.n_ref = 0; 221160f63b49STobias Grosser PPCGArray.refs = nullptr; 221260f63b49STobias Grosser PPCGArray.accessed = true; 2213fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2214fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 221560f63b49STobias Grosser PPCGArray.has_compound_element = false; 221660f63b49STobias Grosser PPCGArray.local = false; 221760f63b49STobias Grosser PPCGArray.declare_local = false; 221860f63b49STobias Grosser PPCGArray.global = false; 221960f63b49STobias Grosser PPCGArray.linearize = false; 222060f63b49STobias Grosser PPCGArray.dep_order = nullptr; 222113c78e4dSTobias Grosser PPCGArray.user = Array; 222260f63b49STobias Grosser 222360f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 22242d010dafSTobias Grosser i++; 2225b9fc860aSTobias Grosser 2226b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 222760f63b49STobias Grosser } 222860f63b49STobias Grosser } 222960f63b49STobias Grosser 223060f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 223160f63b49STobias Grosser /// 223260f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 223360f63b49STobias Grosser isl_union_map *getArrayIdentity() { 223460f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 223560f63b49STobias Grosser 2236d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 223760f63b49STobias Grosser isl_space *Space = Array->getSpace(); 223860f63b49STobias Grosser Space = isl_space_map_from_set(Space); 223960f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 224060f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 224160f63b49STobias Grosser } 224260f63b49STobias Grosser 224360f63b49STobias Grosser return Maps; 224460f63b49STobias Grosser } 224560f63b49STobias Grosser 2246e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2247e938517eSTobias Grosser /// 2248e938517eSTobias Grosser /// @returns A new gpu grogram description. 2249e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2250e938517eSTobias Grosser 2251e938517eSTobias Grosser if (!PPCGScop) 2252e938517eSTobias Grosser return nullptr; 2253e938517eSTobias Grosser 2254e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2255e938517eSTobias Grosser 2256e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2257e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2258aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 225960f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 226060f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 226160f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 226260f63b49STobias Grosser PPCGProg->tagged_must_kill = 226360f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 226460f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 226560f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 2266e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2267e938517eSTobias Grosser PPCGProg->array_order = nullptr; 226869b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 226969b46751STobias Grosser PPCGProg->stmts = getStatements(); 227060f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 227160f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 227260f63b49STobias Grosser PPCGProg->n_array); 227360f63b49STobias Grosser 227460f63b49STobias Grosser createArrays(PPCGProg); 2275e938517eSTobias Grosser 2276d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2277d58acf86STobias Grosser 2278e938517eSTobias Grosser return PPCGProg; 2279e938517eSTobias Grosser } 2280e938517eSTobias Grosser 228169b46751STobias Grosser struct PrintGPUUserData { 228269b46751STobias Grosser struct cuda_info *CudaInfo; 228369b46751STobias Grosser struct gpu_prog *PPCGProg; 228469b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 228569b46751STobias Grosser }; 228669b46751STobias Grosser 228769b46751STobias Grosser /// Print a user statement node in the host code. 228869b46751STobias Grosser /// 228969b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 229069b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 229169b46751STobias Grosser /// host ast. 229269b46751STobias Grosser /// 229369b46751STobias Grosser /// @param P The printer to print to 229469b46751STobias Grosser /// @param Options The printing options to use 229569b46751STobias Grosser /// @param Node The node to print 229669b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 229769b46751STobias Grosser /// expected to be of type PrintGPUUserData. 229869b46751STobias Grosser /// 229969b46751STobias Grosser /// @returns A printer to which the output has been printed. 230069b46751STobias Grosser static __isl_give isl_printer * 230169b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 230269b46751STobias Grosser __isl_take isl_ast_print_options *Options, 230369b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 230469b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 230569b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 230669b46751STobias Grosser 230769b46751STobias Grosser if (Id) { 230820251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 230920251734STobias Grosser 231020251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 231120251734STobias Grosser // otherwise try to call pet functionality that is not available in 231220251734STobias Grosser // Polly. 231320251734STobias Grosser if (IsUser) { 231420251734STobias Grosser P = isl_printer_start_line(P); 231520251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 231620251734STobias Grosser P = isl_printer_end_line(P); 231720251734STobias Grosser isl_id_free(Id); 231820251734STobias Grosser isl_ast_print_options_free(Options); 231920251734STobias Grosser return P; 232020251734STobias Grosser } 232120251734STobias Grosser 232269b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 232369b46751STobias Grosser isl_id_free(Id); 232469b46751STobias Grosser Data->Kernels.push_back(Kernel); 232569b46751STobias Grosser } 232669b46751STobias Grosser 232769b46751STobias Grosser return print_host_user(P, Options, Node, User); 232869b46751STobias Grosser } 232969b46751STobias Grosser 233069b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 233169b46751STobias Grosser /// 233269b46751STobias Grosser /// @param Kernel The kernel to print 233369b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 233469b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 233569b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 233669b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 233769b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 233869b46751STobias Grosser char *String = isl_printer_get_str(P); 233969b46751STobias Grosser printf("%s\n", String); 234069b46751STobias Grosser free(String); 234169b46751STobias Grosser isl_printer_free(P); 234269b46751STobias Grosser } 234369b46751STobias Grosser 234469b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 234569b46751STobias Grosser /// 234669b46751STobias Grosser /// @param Tree An AST describing GPU code 234769b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 234869b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 234969b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 235069b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 235169b46751STobias Grosser 235269b46751STobias Grosser PrintGPUUserData Data; 235369b46751STobias Grosser Data.PPCGProg = PPCGProg; 235469b46751STobias Grosser 235569b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 235669b46751STobias Grosser Options = 235769b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 235869b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 235969b46751STobias Grosser char *String = isl_printer_get_str(P); 236069b46751STobias Grosser printf("# host\n"); 236169b46751STobias Grosser printf("%s\n", String); 236269b46751STobias Grosser free(String); 236369b46751STobias Grosser isl_printer_free(P); 236469b46751STobias Grosser 236569b46751STobias Grosser for (auto Kernel : Data.Kernels) { 236669b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 236769b46751STobias Grosser printKernel(Kernel); 236869b46751STobias Grosser } 236969b46751STobias Grosser } 237069b46751STobias Grosser 2371f384594dSTobias Grosser // Generate a GPU program using PPCG. 2372f384594dSTobias Grosser // 2373f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2374f384594dSTobias Grosser // 2375f384594dSTobias Grosser // 1) Compute new schedule for the program. 2376f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2377f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2378f384594dSTobias Grosser // 2379f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2380f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2381f384594dSTobias Grosser // strategy directly from this pass. 2382f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2383f384594dSTobias Grosser 2384f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2385f384594dSTobias Grosser 2386f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2387f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2388f384594dSTobias Grosser PPCGGen->print = nullptr; 2389f384594dSTobias Grosser PPCGGen->print_user = nullptr; 239060c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2391f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2392f384594dSTobias Grosser PPCGGen->tree = nullptr; 2393f384594dSTobias Grosser PPCGGen->types.n = 0; 2394f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2395f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2396f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2397f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2398f384594dSTobias Grosser 2399f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2400f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2401f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 24022341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2403f384594dSTobias Grosser 2404f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2405f384594dSTobias Grosser 2406aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2407aef5196fSTobias Grosser 240869b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2409aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 241069b46751STobias Grosser } else { 2411aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 241269b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 241369b46751STobias Grosser } 2414aef5196fSTobias Grosser 2415f384594dSTobias Grosser if (DumpSchedule) { 2416f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2417f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2418f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2419f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2420f384594dSTobias Grosser if (Schedule) 2421f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2422f384594dSTobias Grosser else 2423f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2424f384594dSTobias Grosser 2425f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2426f384594dSTobias Grosser isl_printer_free(P); 2427f384594dSTobias Grosser } 2428f384594dSTobias Grosser 242969b46751STobias Grosser if (DumpCode) { 243069b46751STobias Grosser printf("Code\n"); 243169b46751STobias Grosser printf("====\n"); 243269b46751STobias Grosser if (PPCGGen->tree) 243369b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 243469b46751STobias Grosser else 243569b46751STobias Grosser printf("No code generated\n"); 243669b46751STobias Grosser } 243769b46751STobias Grosser 2438f384594dSTobias Grosser isl_schedule_free(Schedule); 2439f384594dSTobias Grosser 2440f384594dSTobias Grosser return PPCGGen; 2441f384594dSTobias Grosser } 2442f384594dSTobias Grosser 2443f384594dSTobias Grosser /// Free gpu_gen structure. 2444f384594dSTobias Grosser /// 2445f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2446f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2447f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2448f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2449f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2450f384594dSTobias Grosser free(PPCGGen); 2451f384594dSTobias Grosser } 2452f384594dSTobias Grosser 2453b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2454b307ed4dSTobias Grosser /// 2455b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2456b307ed4dSTobias Grosser /// ourselves. 2457b307ed4dSTobias Grosser /// 2458b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2459b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2460b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2461b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2462b307ed4dSTobias Grosser free(PPCGScop->options); 2463b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2464b307ed4dSTobias Grosser } 2465b307ed4dSTobias Grosser 246682f2af35STobias Grosser /// Approximate the number of points in the set. 246782f2af35STobias Grosser /// 246882f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 246982f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 247082f2af35STobias Grosser /// 247182f2af35STobias Grosser /// @param Set The set to count. 247282f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 247382f2af35STobias Grosser /// expression. 247482f2af35STobias Grosser /// 247582f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 247682f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 247782f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 247882f2af35STobias Grosser 247982f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 248082f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 248182f2af35STobias Grosser 248282f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 248382f2af35STobias Grosser Space = isl_space_params(Space); 248482f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 248582f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 248682f2af35STobias Grosser 248782f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 248882f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 248982f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 249082f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 249182f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 249282f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 249382f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 249482f2af35STobias Grosser } 249582f2af35STobias Grosser 249682f2af35STobias Grosser isl_set_free(Set); 249782f2af35STobias Grosser isl_pw_aff_free(OneAff); 249882f2af35STobias Grosser 249982f2af35STobias Grosser return Expr; 250082f2af35STobias Grosser } 250182f2af35STobias Grosser 250282f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 250382f2af35STobias Grosser /// statement. 250482f2af35STobias Grosser /// 250582f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 250682f2af35STobias Grosser /// instructions. 250782f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 250882f2af35STobias Grosser /// expression. 250982f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 251082f2af35STobias Grosser /// by @p Stmt. 251182f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 251282f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 251382f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 251482f2af35STobias Grosser 251582f2af35STobias Grosser long InstCount = 0; 251682f2af35STobias Grosser 251782f2af35STobias Grosser if (Stmt.isBlockStmt()) { 251882f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 251982f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 252082f2af35STobias Grosser } else { 252182f2af35STobias Grosser auto *R = Stmt.getRegion(); 252282f2af35STobias Grosser 252382f2af35STobias Grosser for (auto *BB : R->blocks()) { 252482f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 252582f2af35STobias Grosser } 252682f2af35STobias Grosser } 252782f2af35STobias Grosser 252882f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 252982f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 253082f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 253182f2af35STobias Grosser } 253282f2af35STobias Grosser 253382f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 253482f2af35STobias Grosser /// 253582f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 253682f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 253782f2af35STobias Grosser /// expression. 253882f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 253982f2af35STobias Grosser /// in @p S. 254082f2af35STobias Grosser __isl_give isl_ast_expr * 254182f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 254282f2af35STobias Grosser isl_ast_expr *Instructions; 254382f2af35STobias Grosser 254482f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 254582f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 254682f2af35STobias Grosser 254782f2af35STobias Grosser for (ScopStmt &Stmt : S) { 254882f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 254982f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 255082f2af35STobias Grosser } 255182f2af35STobias Grosser return Instructions; 255282f2af35STobias Grosser } 255382f2af35STobias Grosser 255482f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 255582f2af35STobias Grosser /// 255682f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 255782f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 255882f2af35STobias Grosser /// expression. 255982f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 256082f2af35STobias Grosser /// compute and to FALSE, otherwise. 256182f2af35STobias Grosser __isl_give isl_ast_expr * 256282f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 256382f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 256482f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 256582f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 256682f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 256782f2af35STobias Grosser } 256882f2af35STobias Grosser 256938fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 257038fc0aedSTobias Grosser /// 257132837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 257232837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 257332837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 257438fc0aedSTobias Grosser ScopAnnotator Annotator; 257538fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 257638fc0aedSTobias Grosser 257738fc0aedSTobias Grosser Region *R = &S->getRegion(); 257838fc0aedSTobias Grosser 257938fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 258038fc0aedSTobias Grosser 258138fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 258238fc0aedSTobias Grosser 258338fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 258438fc0aedSTobias Grosser 258538fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 258638fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 258738fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 258838fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 258938fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 259038fc0aedSTobias Grosser // code generating this scop. 259138fc0aedSTobias Grosser BasicBlock *StartBlock = 25922d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 259338fc0aedSTobias Grosser 25942d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 2595*17f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 2596acf80064SEli Friedman 259738fc0aedSTobias Grosser // TODO: Handle LICM 259838fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 259938fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 260038fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 2601cb1aef8dSTobias Grosser 2602cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 2603cb1aef8dSTobias Grosser isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build); 260482f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 260582f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 2606cb1aef8dSTobias Grosser isl_ast_build_free(Build); 2607cb1aef8dSTobias Grosser 2608cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 2609cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2610cb1aef8dSTobias Grosser 261138fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 2612fa7b0802STobias Grosser 2613fa7b0802STobias Grosser NodeBuilder.initializeAfterRTH(); 261438fc0aedSTobias Grosser NodeBuilder.create(Root); 26158ed5e599STobias Grosser NodeBuilder.finalize(); 26165857b701STobias Grosser 2617bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 2618bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2619de244eb4STobias Grosser /// point in running it on a GPU. 2620bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 2621bc653f20STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 2622bc653f20STobias Grosser 26235857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 26245857b701STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 262538fc0aedSTobias Grosser } 262638fc0aedSTobias Grosser 2627e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 2628e938517eSTobias Grosser S = &CurrentScop; 262938fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 263038fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 263138fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 26327b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 263338fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2634e938517eSTobias Grosser 26352d58a64eSTobias Grosser // We currently do not support scops with invariant loads. 26362d58a64eSTobias Grosser if (S->hasInvariantAccesses()) 26372d58a64eSTobias Grosser return false; 26382d58a64eSTobias Grosser 2639e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 2640e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 2641f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 264238fc0aedSTobias Grosser 264338fc0aedSTobias Grosser if (PPCGGen->tree) 264432837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 264538fc0aedSTobias Grosser 2646b307ed4dSTobias Grosser freeOptions(PPCGScop); 2647f384594dSTobias Grosser freePPCGGen(PPCGGen); 2648e938517eSTobias Grosser gpu_prog_free(PPCGProg); 2649e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 2650e938517eSTobias Grosser 2651e938517eSTobias Grosser return true; 2652e938517eSTobias Grosser } 26539dfe4e7cSTobias Grosser 26549dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 26559dfe4e7cSTobias Grosser 26569dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 26579dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 26589dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 26599dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 26609dfe4e7cSTobias Grosser AU.addRequired<ScopDetection>(); 26619dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 26629dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 26639dfe4e7cSTobias Grosser 26649dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 26659dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 26669dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 26679dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 26689dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 26699dfe4e7cSTobias Grosser AU.addPreserved<ScopDetection>(); 26709dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 26719dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 26729dfe4e7cSTobias Grosser 26739dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 26749dfe4e7cSTobias Grosser // region tree. 26759dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 26769dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 26779dfe4e7cSTobias Grosser } 26789dfe4e7cSTobias Grosser }; 267924222c73STobias Grosser } // namespace 26809dfe4e7cSTobias Grosser 26819dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 26829dfe4e7cSTobias Grosser 2683*17f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 2684*17f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 2685*17f01968SSiddharth Bhat generator->Runtime = Runtime; 2686*17f01968SSiddharth Bhat generator->Architecture = Arch; 2687*17f01968SSiddharth Bhat return generator; 2688*17f01968SSiddharth Bhat } 26899dfe4e7cSTobias Grosser 26909dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 26919dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 26929dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 26939dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 26949dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 26959dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 26969dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 26979dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection); 26989dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 26999dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 2700