19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 29dfe4e7cSTobias Grosser // 39dfe4e7cSTobias Grosser // The LLVM Compiler Infrastructure 49dfe4e7cSTobias Grosser // 59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source 69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details. 79dfe4e7cSTobias Grosser // 89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 99dfe4e7cSTobias Grosser // 109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg 119dfe4e7cSTobias Grosser // GPU mapping strategy. 129dfe4e7cSTobias Grosser // 139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 149dfe4e7cSTobias Grosser 1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h" 16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 21f384594dSTobias Grosser #include "polly/Options.h" 22629109b6STobias Grosser #include "polly/ScopDetection.h" 239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 33e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 399dfe4e7cSTobias Grosser 40f384594dSTobias Grosser #include "isl/union_map.h" 41f384594dSTobias Grosser 42e938517eSTobias Grosser extern "C" { 43a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 44a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 47a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 48e938517eSTobias Grosser } 49e938517eSTobias Grosser 509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 519dfe4e7cSTobias Grosser 529dfe4e7cSTobias Grosser using namespace polly; 539dfe4e7cSTobias Grosser using namespace llvm; 549dfe4e7cSTobias Grosser 559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 569dfe4e7cSTobias Grosser 57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 58f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 59681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 60f384594dSTobias Grosser cl::cat(PollyCategory)); 6169b46751STobias Grosser 6269b46751STobias Grosser static cl::opt<bool> 6369b46751STobias Grosser DumpCode("polly-acc-dump-code", 6469b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6569b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6669b46751STobias Grosser 6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6832837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6932837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7032837fe3STobias Grosser cl::cat(PollyCategory)); 7132837fe3STobias Grosser 7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7374dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7474dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7574dc3cb4STobias Grosser cl::cat(PollyCategory)); 7674dc3cb4STobias Grosser 7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7874dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7974dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8074dc3cb4STobias Grosser cl::cat(PollyCategory)); 81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 82b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 83b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 84b513b491STobias Grosser cl::cat(PollyCategory)); 85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 86130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 87130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 88130ca30fSTobias Grosser cl::cat(PollyCategory)); 8974dc3cb4STobias Grosser 90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 92abed4969SSiddharth Bhat " that all memory has been" 93abed4969SSiddharth Bhat " declared as managed memory"), 94abed4969SSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 95abed4969SSiddharth Bhat cl::cat(PollyCategory)); 96abed4969SSiddharth Bhat 9765d7f72fSSiddharth Bhat static cl::opt<bool> 9865d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 9965d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10065d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10165d7f72fSSiddharth Bhat " kernel module."), 10265d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10365d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 10465d7f72fSSiddharth Bhat 10574dc3cb4STobias Grosser static cl::opt<std::string> 10674dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 10774dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 10874dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 10974dc3cb4STobias Grosser 11082f2af35STobias Grosser static cl::opt<int> 11182f2af35STobias Grosser MinCompute("polly-acc-mincompute", 11282f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 11382f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 11482f2af35STobias Grosser 115a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 116a82f2d26SSiddharth Bhat /// used by live range reordering. 117a82f2d26SSiddharth Bhat /// 118a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 119a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 120a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 121a82f2d26SSiddharth Bhat struct MustKillsInfo { 122a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 123a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 124a82f2d26SSiddharth Bhat /// 125a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 127a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 128a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 129a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 130a82f2d26SSiddharth Bhat /// killed. 131a82f2d26SSiddharth Bhat /// 132a82f2d26SSiddharth Bhat /// We currently only derive kill information for phi nodes, as phi nodes 133a82f2d26SSiddharth Bhat /// allow us to easily derive kill information. PHI nodes are not alive 134a82f2d26SSiddharth Bhat /// outside the scop and can consequently all be "killed". [params] -> { 135a82f2d26SSiddharth Bhat /// [Stmt_phantom[] -> ref_phantom[]] -> phi_ref[] } 136a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 137a82f2d26SSiddharth Bhat 138a82f2d26SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr), TaggedMustKills(nullptr){}; 139a82f2d26SSiddharth Bhat }; 140a82f2d26SSiddharth Bhat 141a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 142a82f2d26SSiddharth Bhat /// 143a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 144a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 145a82f2d26SSiddharth Bhat /// PPCG. 146a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 147a82f2d26SSiddharth Bhat const isl::space ParamSpace(isl::manage(S.getParamSpace())); 148a82f2d26SSiddharth Bhat MustKillsInfo Info; 149a82f2d26SSiddharth Bhat 150a82f2d26SSiddharth Bhat // 1. Collect phi nodes in scop. 151a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 152a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 153a82f2d26SSiddharth Bhat if (!SAI->isPHIKind()) 154a82f2d26SSiddharth Bhat continue; 155a82f2d26SSiddharth Bhat 156a82f2d26SSiddharth Bhat KillMemIds.push_back(isl::manage(SAI->getBasePtrId())); 157a82f2d26SSiddharth Bhat } 158a82f2d26SSiddharth Bhat 159a82f2d26SSiddharth Bhat Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 160a82f2d26SSiddharth Bhat 161a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 162a82f2d26SSiddharth Bhat // schedule: 163a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 164a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 165a82f2d26SSiddharth Bhat // at the cost of some code complexity. 166a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 167a82f2d26SSiddharth Bhat 168a82f2d26SSiddharth Bhat for (isl::id &phiId : KillMemIds) { 169a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 170a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("SKill_phantom_").append(phiId.get_name()), 171a82f2d26SSiddharth Bhat nullptr); 172a82f2d26SSiddharth Bhat 173a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 174a82f2d26SSiddharth Bhat // 2. We need to construct a map: 175a82f2d26SSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> phi_ref } 176a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 177a82f2d26SSiddharth Bhat // 2a. StmtToPhi: 178a82f2d26SSiddharth Bhat // [param] -> { Stmt_phantom[] -> phi_ref[] } 179a82f2d26SSiddharth Bhat // 2b. PhantomRefToPhi: 180a82f2d26SSiddharth Bhat // [param] -> { ref_phantom[] -> phi_ref[] } 181a82f2d26SSiddharth Bhat // 182a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 183a82f2d26SSiddharth Bhat // TaggedMustKill: 184a82f2d26SSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 185a82f2d26SSiddharth Bhat 186a82f2d26SSiddharth Bhat // 2a. [param] -> { S_2[] -> phi_ref[] } 187a82f2d26SSiddharth Bhat isl::map StmtToPhi = isl::map::universe(isl::space(ParamSpace)); 188a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 189a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::out, isl::id(phiId)); 190a82f2d26SSiddharth Bhat 191a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 192a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + phiId.get_name(), nullptr); 193a82f2d26SSiddharth Bhat 194a82f2d26SSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> memref[] } 195a82f2d26SSiddharth Bhat isl::map PhantomRefToPhi = isl::map::universe(isl::space(ParamSpace)); 196a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::in, PhantomRefId); 197a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::out, phiId); 198a82f2d26SSiddharth Bhat 199a82f2d26SSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 200a82f2d26SSiddharth Bhat isl::map TaggedMustKill = StmtToPhi.domain_product(PhantomRefToPhi); 201a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 202a82f2d26SSiddharth Bhat 203a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 204a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 205a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 206a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 207a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 208a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 209a82f2d26SSiddharth Bhat 210a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 211a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 212a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 213a82f2d26SSiddharth Bhat else 214a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 215a82f2d26SSiddharth Bhat } 216a82f2d26SSiddharth Bhat 217a82f2d26SSiddharth Bhat return Info; 218a82f2d26SSiddharth Bhat } 219a82f2d26SSiddharth Bhat 22060c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 22160c60025STobias Grosser /// 22260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 22360c60025STobias Grosser /// of the scheduled ScopStmts. 22460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 225edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 22660c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 22760c60025STobias Grosser isl_id *Id, void *User), 22860c60025STobias Grosser void *UserIndex, 22960c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 230edb885cbSTobias Grosser void *UserExpr) { 23160c60025STobias Grosser 232edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 23360c60025STobias Grosser 234edb885cbSTobias Grosser isl_ctx *Ctx; 235edb885cbSTobias Grosser 236edb885cbSTobias Grosser if (!Stmt || !Build) 237edb885cbSTobias Grosser return NULL; 238edb885cbSTobias Grosser 239edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 240edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 241edb885cbSTobias Grosser 242edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 243edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 244edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 245edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 246edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 247edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 248edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 249edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 250edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 251edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 252edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 253edb885cbSTobias Grosser } 254edb885cbSTobias Grosser 255edb885cbSTobias Grosser return RefToExpr; 25660c60025STobias Grosser } 257f384594dSTobias Grosser 258a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 259a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 260a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 261a90be207SSiddharth Bhat if (bytes == 0) 262a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 263a90be207SSiddharth Bhat return bytes; 264a90be207SSiddharth Bhat } 265a90be207SSiddharth Bhat 26638fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 26738fc0aedSTobias Grosser /// 26838fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 269a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 27038fc0aedSTobias Grosser /// for generating GPU specific user nodes. 27138fc0aedSTobias Grosser /// 27238fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 27338fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 27438fc0aedSTobias Grosser public: 2752d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 27638fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 277acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 27817f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 2792d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 28017f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 281edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 282edb885cbSTobias Grosser } 28338fc0aedSTobias Grosser 284fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 285fa7b0802STobias Grosser void initializeAfterRTH(); 286fa7b0802STobias Grosser 287fa7b0802STobias Grosser /// Finalize the generated scop. 288fa7b0802STobias Grosser virtual void finalize(); 289fa7b0802STobias Grosser 2905857b701STobias Grosser /// Track if the full build process was successful. 2915857b701STobias Grosser /// 2925857b701STobias Grosser /// This value is set to false, if throughout the build process an error 2935857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 2945857b701STobias Grosser bool BuildSuccessful = true; 2955857b701STobias Grosser 296bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 297bc653f20STobias Grosser unsigned DeepestSequential = 0; 298bc653f20STobias Grosser 299bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 300bc653f20STobias Grosser unsigned DeepestParallel = 0; 301bc653f20STobias Grosser 302*79f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 303*79f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 304*79f13b9aSSingapuram Sanjay Srivallabh 30538fc0aedSTobias Grosser private: 30674dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 30774dc3cb4STobias Grosser /// 30874dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 30974dc3cb4STobias Grosser /// more. 31074dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 31174dc3cb4STobias Grosser 31213c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 31313c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3147287aeddSTobias Grosser 315fa7b0802STobias Grosser /// The current GPU context. 316fa7b0802STobias Grosser Value *GPUContext; 317fa7b0802STobias Grosser 318b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 319b513b491STobias Grosser std::vector<isl_id *> KernelIds; 320b513b491STobias Grosser 32132837fe3STobias Grosser /// A module containing GPU code. 32232837fe3STobias Grosser /// 32332837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 32432837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 32532837fe3STobias Grosser 32632837fe3STobias Grosser /// The GPU program we generate code for. 32732837fe3STobias Grosser gpu_prog *Prog; 32832837fe3STobias Grosser 32917f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 33017f01968SSiddharth Bhat GPURuntime Runtime; 33117f01968SSiddharth Bhat 33217f01968SSiddharth Bhat /// The GPU Architecture to target. 33317f01968SSiddharth Bhat GPUArch Arch; 33417f01968SSiddharth Bhat 335472f9654STobias Grosser /// Class to free isl_ids. 336472f9654STobias Grosser class IslIdDeleter { 337472f9654STobias Grosser public: 338472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 339472f9654STobias Grosser }; 340472f9654STobias Grosser 341472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 342472f9654STobias Grosser /// 343472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 344472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 345472f9654STobias Grosser 346edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 347edb885cbSTobias Grosser 34838fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 34938fc0aedSTobias Grosser /// 35038fc0aedSTobias Grosser /// These AST nodes can be of type: 35138fc0aedSTobias Grosser /// 35238fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 35338fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 35413c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 3555260c041STobias Grosser /// - In-kernel synchronization 3565260c041STobias Grosser /// - In-kernel memory copy statement 35738fc0aedSTobias Grosser /// 3581fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 3591fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 36032837fe3STobias Grosser 36113c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 36213c78e4dSTobias Grosser 36313c78e4dSTobias Grosser /// Create code for a data transfer statement 36413c78e4dSTobias Grosser /// 36513c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 36613c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 36713c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 36813c78e4dSTobias Grosser enum DataDirection Direction); 36913c78e4dSTobias Grosser 370edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 371edb885cbSTobias Grosser /// 372edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 373edb885cbSTobias Grosser /// 374f291c8d5SSiddharth Bhat /// @returns A pair, whose first element contains the set of values 375f291c8d5SSiddharth Bhat /// referenced by the kernel, and whose second element contains the 376f291c8d5SSiddharth Bhat /// set of functions referenced by the kernel. All functions in the 377f291c8d5SSiddharth Bhat /// second set satisfy isValidFunctionInKernel. 378f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 379f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 380edb885cbSTobias Grosser 38179a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 38279a947c2STobias Grosser /// 38379a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 38479a947c2STobias Grosser /// 38579a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 38679a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 38779a947c2STobias Grosser 388abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 389abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 390abed4969SSiddharth Bhat /// host pointers to the device. 391abed4969SSiddharth Bhat /// \note 392abed4969SSiddharth Bhat /// This is to be used only with managed memory 393abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 394abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 395abed4969SSiddharth Bhat 39679a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 39779a947c2STobias Grosser /// 39879a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 39979a947c2STobias Grosser /// 40079a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 40179a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 40279a947c2STobias Grosser 403a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 404a90be207SSiddharth Bhat /// parameters. 405a90be207SSiddharth Bhat /// 406a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 407a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 408a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 409a90be207SSiddharth Bhat /// parameter. 410a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 411a90be207SSiddharth Bhat int Index); 412a90be207SSiddharth Bhat 41379a947c2STobias Grosser /// Create kernel launch parameters. 41479a947c2STobias Grosser /// 41579a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 41679a947c2STobias Grosser /// @param F The kernel function that has been created. 41757693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 41879a947c2STobias Grosser /// 41979a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 42079a947c2STobias Grosser /// values that are passed to the kernel. 42157693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 42257693272STobias Grosser SetVector<Value *> SubtreeValues); 42379a947c2STobias Grosser 424b513b491STobias Grosser /// Create declarations for kernel variable. 425b513b491STobias Grosser /// 426b513b491STobias Grosser /// This includes shared memory declarations. 427b513b491STobias Grosser /// 428b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 429b513b491STobias Grosser /// @param FN The function into which to generate the variables. 430b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 431b513b491STobias Grosser 432c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 433c1c6a2a6STobias Grosser /// 434c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 435c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 436c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 437c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 438c1c6a2a6STobias Grosser /// as specified here. 439c1c6a2a6STobias Grosser /// 440c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 441c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 442c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 443c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 444c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 445c1c6a2a6STobias Grosser Value *BlockDimZ); 446c1c6a2a6STobias Grosser 44732837fe3STobias Grosser /// Create GPU kernel. 44832837fe3STobias Grosser /// 44932837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 45032837fe3STobias Grosser /// 45132837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 45232837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 45332837fe3STobias Grosser 45413c78e4dSTobias Grosser /// Generate code that computes the size of an array. 45513c78e4dSTobias Grosser /// 45613c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 45713c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 45813c78e4dSTobias Grosser 459aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 460aaabbbf8STobias Grosser /// 461aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 462aaabbbf8STobias Grosser /// 463aaabbbf8STobias Grosser /// Example: 464aaabbbf8STobias Grosser /// 465aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 466aaabbbf8STobias Grosser /// A[i + 42] += ... 467aaabbbf8STobias Grosser /// 468aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 469aaabbbf8STobias Grosser /// 470aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 471aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 472aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 473aaabbbf8STobias Grosser 47400bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 47500bb5a99STobias Grosser /// 47600bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 47700bb5a99STobias Grosser /// @param FN The function created for the kernel. 47800bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 47900bb5a99STobias Grosser 48032837fe3STobias Grosser /// Create kernel function. 48132837fe3STobias Grosser /// 48232837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 48332837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 48432837fe3STobias Grosser /// start block of this newly created function. 48532837fe3STobias Grosser /// 48632837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 487edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 488f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 489f291c8d5SSiddharth Bhat /// kernel. 490edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 491f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 492f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 49332837fe3STobias Grosser 49432837fe3STobias Grosser /// Create the declaration of a kernel function. 49532837fe3STobias Grosser /// 49632837fe3STobias Grosser /// The kernel function takes as arguments: 49732837fe3STobias Grosser /// 49832837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 499f6044bd0STobias Grosser /// - Host iterators 500c84a1995STobias Grosser /// - Parameters 50132837fe3STobias Grosser /// - Other LLVM Value references (TODO) 50232837fe3STobias Grosser /// 50332837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 504edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 505edb885cbSTobias Grosser /// 50632837fe3STobias Grosser /// @returns The newly declared function. 507edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 508edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 50932837fe3STobias Grosser 510472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 511472f9654STobias Grosser /// 512472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 513472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 514472f9654STobias Grosser 515f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 516f291c8d5SSiddharth Bhat /// 517f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 518f291c8d5SSiddharth Bhat /// SubtreeFunctions. 519f291c8d5SSiddharth Bhat /// 520f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 521f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 522f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 523f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 524f291c8d5SSiddharth Bhat /// 525f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 526f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 527f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 528f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 529f291c8d5SSiddharth Bhat /// 530f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 531f291c8d5SSiddharth Bhat /// this kernel. 532f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 533f291c8d5SSiddharth Bhat 534b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 535b513b491STobias Grosser /// 536b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 537b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 538b513b491STobias Grosser 539edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 540edb885cbSTobias Grosser /// 541edb885cbSTobias Grosser /// @param Expr The expression containing the call. 542edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 543edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 544edb885cbSTobias Grosser 5455260c041STobias Grosser /// Create an in-kernel synchronization call. 5465260c041STobias Grosser void createKernelSync(); 5475260c041STobias Grosser 54874dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 54974dc3cb4STobias Grosser /// 55074dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 55174dc3cb4STobias Grosser std::string createKernelASM(); 55274dc3cb4STobias Grosser 55374dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 55474dc3cb4STobias Grosser /// 55574dc3cb4STobias Grosser /// @param F The function to remove references to. 55674dc3cb4STobias Grosser void clearDominators(Function *F); 55774dc3cb4STobias Grosser 55874dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 55974dc3cb4STobias Grosser /// 56074dc3cb4STobias Grosser /// @param F The function to remove references to. 56174dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 56274dc3cb4STobias Grosser 56374dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 56474dc3cb4STobias Grosser /// 56574dc3cb4STobias Grosser /// @param F The function to remove references to. 56674dc3cb4STobias Grosser void clearLoops(Function *F); 56774dc3cb4STobias Grosser 56832837fe3STobias Grosser /// Finalize the generation of the kernel function. 56932837fe3STobias Grosser /// 57032837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 57132837fe3STobias Grosser /// dump its IR to stderr. 57257793596STobias Grosser /// 57357793596STobias Grosser /// @returns The Assembly string of the kernel. 57457793596STobias Grosser std::string finalizeKernelFunction(); 575fa7b0802STobias Grosser 57651dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 57751dfc275STobias Grosser /// 57851dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 579a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 58051dfc275STobias Grosser /// the kernel terminates. 58151dfc275STobias Grosser /// 58251dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 58351dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 58451dfc275STobias Grosser 5857287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 586fa7b0802STobias Grosser void allocateDeviceArrays(); 587fa7b0802STobias Grosser 5887287aeddSTobias Grosser /// Free all allocated device arrays. 5897287aeddSTobias Grosser void freeDeviceArrays(); 5907287aeddSTobias Grosser 591fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 592fa7b0802STobias Grosser /// 593fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 594fa7b0802STobias Grosser Value *createCallInitContext(); 595fa7b0802STobias Grosser 59679a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 59779a947c2STobias Grosser /// 59879a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 59979a947c2STobias Grosser /// 60079a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 60179a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 60279a947c2STobias Grosser 603fa7b0802STobias Grosser /// Create a call to free the GPU context. 604fa7b0802STobias Grosser /// 605fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 606fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 607fa7b0802STobias Grosser 6087287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6097287aeddSTobias Grosser /// 6107287aeddSTobias Grosser /// @param Size The size of memory to allocate 6117287aeddSTobias Grosser /// 6127287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 613fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6147287aeddSTobias Grosser 6157287aeddSTobias Grosser /// Create a call to free a device array. 6167287aeddSTobias Grosser /// 6177287aeddSTobias Grosser /// @param Array The device array to free. 6187287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 61913c78e4dSTobias Grosser 62013c78e4dSTobias Grosser /// Create a call to copy data from host to device. 62113c78e4dSTobias Grosser /// 62213c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 62313c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 62413c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 62513c78e4dSTobias Grosser Value *Size); 62613c78e4dSTobias Grosser 62713c78e4dSTobias Grosser /// Create a call to copy data from device to host. 62813c78e4dSTobias Grosser /// 62913c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 63013c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 63113c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 63213c78e4dSTobias Grosser Value *Size); 63357793596STobias Grosser 634abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 635abed4969SSiddharth Bhat /// \note 636abed4969SSiddharth Bhat /// This is to be used only with managed memory. 637abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 638abed4969SSiddharth Bhat 63957793596STobias Grosser /// Create a call to get a kernel from an assembly string. 64057793596STobias Grosser /// 64157793596STobias Grosser /// @param Buffer The string describing the kernel. 64257793596STobias Grosser /// @param Entry The name of the kernel function to call. 64357793596STobias Grosser /// 64457793596STobias Grosser /// @returns A pointer to a kernel object 64557793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 64657793596STobias Grosser 64757793596STobias Grosser /// Create a call to free a GPU kernel. 64857793596STobias Grosser /// 64957793596STobias Grosser /// @param GPUKernel THe kernel to free. 65057793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 65179a947c2STobias Grosser 65279a947c2STobias Grosser /// Create a call to launch a GPU kernel. 65379a947c2STobias Grosser /// 65479a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 65579a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 65679a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 65779a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 65879a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 65979a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 660a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 66179a947c2STobias Grosser /// the parameter values passed for each kernel argument. 66279a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 66379a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 66479a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 66579a947c2STobias Grosser Value *Parameters); 6661fb9b64dSTobias Grosser }; 6671fb9b64dSTobias Grosser 668*79f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 669*79f13b9aSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_KERNEL_" + 670*79f13b9aSSingapuram Sanjay Srivallabh std::to_string(Kernel_id); 671*79f13b9aSSingapuram Sanjay Srivallabh } 672*79f13b9aSSingapuram Sanjay Srivallabh 673fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 674750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 675750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 676750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 677750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 678750160e2STobias Grosser 679fa7b0802STobias Grosser GPUContext = createCallInitContext(); 680abed4969SSiddharth Bhat 681abed4969SSiddharth Bhat if (!ManagedMemory) 682fa7b0802STobias Grosser allocateDeviceArrays(); 683fa7b0802STobias Grosser } 684fa7b0802STobias Grosser 685fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 686abed4969SSiddharth Bhat if (!ManagedMemory) 6877287aeddSTobias Grosser freeDeviceArrays(); 688abed4969SSiddharth Bhat 689fa7b0802STobias Grosser createCallFreeContext(GPUContext); 690fa7b0802STobias Grosser IslNodeBuilder::finalize(); 691fa7b0802STobias Grosser } 692fa7b0802STobias Grosser 693fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 694abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 695abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 696fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 697fa7b0802STobias Grosser 698fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 699fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 70013c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7017287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7027287aeddSTobias Grosser DevArrayName.append(Array->name); 703fa7b0802STobias Grosser 70413c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 705aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 706aaabbbf8STobias Grosser if (Offset) 707aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 708aaabbbf8STobias Grosser ArraySize, 709aaabbbf8STobias Grosser Builder.CreateMul(Offset, 710aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 7117287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7127287aeddSTobias Grosser DevArray->setName(DevArrayName); 71313c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 714fa7b0802STobias Grosser } 715fa7b0802STobias Grosser 716fa7b0802STobias Grosser isl_ast_build_free(Build); 717fa7b0802STobias Grosser } 718fa7b0802STobias Grosser 719c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 720c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 721c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 722c1c6a2a6STobias Grosser 723c1c6a2a6STobias Grosser for (auto &F : *M) { 724c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 725c1c6a2a6STobias Grosser continue; 726c1c6a2a6STobias Grosser 727c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 728c1c6a2a6STobias Grosser 729c1c6a2a6STobias Grosser Metadata *Elements[] = { 730c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 731c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 732c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 733c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 734c1c6a2a6STobias Grosser }; 735c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 736c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 737c1c6a2a6STobias Grosser } 738c1c6a2a6STobias Grosser } 739c1c6a2a6STobias Grosser 7407287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 741abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 74213c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 74313c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 7447287aeddSTobias Grosser } 7457287aeddSTobias Grosser 74657793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 74757793596STobias Grosser const char *Name = "polly_getKernel"; 74857793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 74957793596STobias Grosser Function *F = M->getFunction(Name); 75057793596STobias Grosser 75157793596STobias Grosser // If F is not available, declare it. 75257793596STobias Grosser if (!F) { 75357793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 75457793596STobias Grosser std::vector<Type *> Args; 75557793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 75657793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 75757793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 75857793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 75957793596STobias Grosser } 76057793596STobias Grosser 76157793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 76257793596STobias Grosser } 76357793596STobias Grosser 76479a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 76579a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 76679a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 76779a947c2STobias Grosser Function *F = M->getFunction(Name); 76879a947c2STobias Grosser 76979a947c2STobias Grosser // If F is not available, declare it. 77079a947c2STobias Grosser if (!F) { 77179a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 77279a947c2STobias Grosser std::vector<Type *> Args; 77379a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 77479a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 77579a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 77679a947c2STobias Grosser } 77779a947c2STobias Grosser 77879a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 77979a947c2STobias Grosser } 78079a947c2STobias Grosser 78179a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 78279a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 78379a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 78479a947c2STobias Grosser Value *Parameters) { 78579a947c2STobias Grosser const char *Name = "polly_launchKernel"; 78679a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 78779a947c2STobias Grosser Function *F = M->getFunction(Name); 78879a947c2STobias Grosser 78979a947c2STobias Grosser // If F is not available, declare it. 79079a947c2STobias Grosser if (!F) { 79179a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 79279a947c2STobias Grosser std::vector<Type *> Args; 79379a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79479a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79579a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79779a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79879a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79979a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 80079a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 80179a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 80279a947c2STobias Grosser } 80379a947c2STobias Grosser 804ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 80579a947c2STobias Grosser BlockDimZ, Parameters}); 80679a947c2STobias Grosser } 80779a947c2STobias Grosser 80857793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 80957793596STobias Grosser const char *Name = "polly_freeKernel"; 81057793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 81157793596STobias Grosser Function *F = M->getFunction(Name); 81257793596STobias Grosser 81357793596STobias Grosser // If F is not available, declare it. 81457793596STobias Grosser if (!F) { 81557793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 81657793596STobias Grosser std::vector<Type *> Args; 81757793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 81857793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 81957793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 82057793596STobias Grosser } 82157793596STobias Grosser 82257793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 82357793596STobias Grosser } 82457793596STobias Grosser 8257287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 826abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 827abed4969SSiddharth Bhat "for device"); 8287287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 8297287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8307287aeddSTobias Grosser Function *F = M->getFunction(Name); 8317287aeddSTobias Grosser 8327287aeddSTobias Grosser // If F is not available, declare it. 8337287aeddSTobias Grosser if (!F) { 8347287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 8357287aeddSTobias Grosser std::vector<Type *> Args; 8367287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 8377287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 8387287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 8397287aeddSTobias Grosser } 8407287aeddSTobias Grosser 8417287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 8427287aeddSTobias Grosser } 8437287aeddSTobias Grosser 844fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 845abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 846abed4969SSiddharth Bhat "for device"); 847fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 848fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 849fa7b0802STobias Grosser Function *F = M->getFunction(Name); 850fa7b0802STobias Grosser 851fa7b0802STobias Grosser // If F is not available, declare it. 852fa7b0802STobias Grosser if (!F) { 853fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 854fa7b0802STobias Grosser std::vector<Type *> Args; 855fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 856fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 857fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 858fa7b0802STobias Grosser } 859fa7b0802STobias Grosser 860fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 861fa7b0802STobias Grosser } 862fa7b0802STobias Grosser 86313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 86413c78e4dSTobias Grosser Value *DeviceData, 86513c78e4dSTobias Grosser Value *Size) { 866abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 867abed4969SSiddharth Bhat "device and host"); 86813c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 86913c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 87013c78e4dSTobias Grosser Function *F = M->getFunction(Name); 87113c78e4dSTobias Grosser 87213c78e4dSTobias Grosser // If F is not available, declare it. 87313c78e4dSTobias Grosser if (!F) { 87413c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 87513c78e4dSTobias Grosser std::vector<Type *> Args; 87613c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87713c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87813c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 87913c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 88013c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 88113c78e4dSTobias Grosser } 88213c78e4dSTobias Grosser 88313c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 88413c78e4dSTobias Grosser } 88513c78e4dSTobias Grosser 88613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 88713c78e4dSTobias Grosser Value *HostData, 88813c78e4dSTobias Grosser Value *Size) { 889abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 890abed4969SSiddharth Bhat "device and host"); 89113c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 89213c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 89313c78e4dSTobias Grosser Function *F = M->getFunction(Name); 89413c78e4dSTobias Grosser 89513c78e4dSTobias Grosser // If F is not available, declare it. 89613c78e4dSTobias Grosser if (!F) { 89713c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 89813c78e4dSTobias Grosser std::vector<Type *> Args; 89913c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90013c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90113c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 90213c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 90313c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 90413c78e4dSTobias Grosser } 90513c78e4dSTobias Grosser 90613c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 90713c78e4dSTobias Grosser } 90813c78e4dSTobias Grosser 909abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 910abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 911abed4969SSiddharth Bhat "managed memory"); 912abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 913abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 914abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 915abed4969SSiddharth Bhat 916abed4969SSiddharth Bhat // If F is not available, declare it. 917abed4969SSiddharth Bhat if (!F) { 918abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 919abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 920abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 921abed4969SSiddharth Bhat } 922abed4969SSiddharth Bhat 923abed4969SSiddharth Bhat Builder.CreateCall(F); 924abed4969SSiddharth Bhat } 925abed4969SSiddharth Bhat 926fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 92717f01968SSiddharth Bhat const char *Name; 92817f01968SSiddharth Bhat 92917f01968SSiddharth Bhat switch (Runtime) { 93017f01968SSiddharth Bhat case GPURuntime::CUDA: 93117f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 93217f01968SSiddharth Bhat break; 93317f01968SSiddharth Bhat case GPURuntime::OpenCL: 93417f01968SSiddharth Bhat Name = "polly_initContextCL"; 93517f01968SSiddharth Bhat break; 93617f01968SSiddharth Bhat } 93717f01968SSiddharth Bhat 938fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 939fa7b0802STobias Grosser Function *F = M->getFunction(Name); 940fa7b0802STobias Grosser 941fa7b0802STobias Grosser // If F is not available, declare it. 942fa7b0802STobias Grosser if (!F) { 943fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 944fa7b0802STobias Grosser std::vector<Type *> Args; 945fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 946fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 947fa7b0802STobias Grosser } 948fa7b0802STobias Grosser 949fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 950fa7b0802STobias Grosser } 951fa7b0802STobias Grosser 952fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 953fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 954fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 955fa7b0802STobias Grosser Function *F = M->getFunction(Name); 956fa7b0802STobias Grosser 957fa7b0802STobias Grosser // If F is not available, declare it. 958fa7b0802STobias Grosser if (!F) { 959fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 960fa7b0802STobias Grosser std::vector<Type *> Args; 961fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 962fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 963fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 964fa7b0802STobias Grosser } 965fa7b0802STobias Grosser 966fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 967fa7b0802STobias Grosser } 968fa7b0802STobias Grosser 9695260c041STobias Grosser /// Check if one string is a prefix of another. 9705260c041STobias Grosser /// 9715260c041STobias Grosser /// @param String The string in which to look for the prefix. 9725260c041STobias Grosser /// @param Prefix The prefix to look for. 9735260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 9745260c041STobias Grosser return String.find(Prefix) == 0; 9755260c041STobias Grosser } 9765260c041STobias Grosser 97713c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 97813c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 97913c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 98013c78e4dSTobias Grosser 98113c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 98213c78e4dSTobias Grosser auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 98313c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 98413c78e4dSTobias Grosser 98513c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 98613c78e4dSTobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 98713c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 98813c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 98913c78e4dSTobias Grosser } 99013c78e4dSTobias Grosser 99113c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 992b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 993b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 99413c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 99513c78e4dSTobias Grosser } 99613c78e4dSTobias Grosser isl_ast_build_free(Build); 99713c78e4dSTobias Grosser return ArraySize; 99813c78e4dSTobias Grosser } 99913c78e4dSTobias Grosser 1000aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1001aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1002aaabbbf8STobias Grosser return nullptr; 1003aaabbbf8STobias Grosser 1004aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1005aaabbbf8STobias Grosser 1006aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1007aaabbbf8STobias Grosser 1008aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1009aaabbbf8STobias Grosser 1010aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1011aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1012aaabbbf8STobias Grosser 1013aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 1014aaabbbf8STobias Grosser isl_set_free(Min); 1015aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1016aaabbbf8STobias Grosser isl_ast_build_free(Build); 1017aaabbbf8STobias Grosser return nullptr; 1018aaabbbf8STobias Grosser } 1019aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1020aaabbbf8STobias Grosser 1021aaabbbf8STobias Grosser isl_ast_expr *Result = 1022aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1023aaabbbf8STobias Grosser 1024aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1025aaabbbf8STobias Grosser if (i > 0) { 1026aaabbbf8STobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 1027aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1028aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 1029aaabbbf8STobias Grosser } 1030aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1031aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1032aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 1033aaabbbf8STobias Grosser } 1034aaabbbf8STobias Grosser 1035aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 1036aaabbbf8STobias Grosser isl_set_free(Min); 1037aaabbbf8STobias Grosser isl_ast_build_free(Build); 1038aaabbbf8STobias Grosser 1039aaabbbf8STobias Grosser return ResultValue; 1040aaabbbf8STobias Grosser } 1041aaabbbf8STobias Grosser 1042abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1043abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1044abed4969SSiddharth Bhat 1045abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 1046abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1047abed4969SSiddharth Bhat "with managed memory"); 1048abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1049abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1050abed4969SSiddharth Bhat return it->second; 1051abed4969SSiddharth Bhat } else { 1052abed4969SSiddharth Bhat Value *HostPtr; 1053abed4969SSiddharth Bhat 1054abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 1055abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1056abed4969SSiddharth Bhat else 1057abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 1058abed4969SSiddharth Bhat 1059abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 1060abed4969SSiddharth Bhat if (Offset) { 1061abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 1062abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1063abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 1064abed4969SSiddharth Bhat } 1065abed4969SSiddharth Bhat 1066abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1067abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 1068abed4969SSiddharth Bhat return HostPtr; 1069abed4969SSiddharth Bhat } 1070abed4969SSiddharth Bhat } 1071abed4969SSiddharth Bhat 107213c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 107313c78e4dSTobias Grosser enum DataDirection Direction) { 1074abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 107513c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 107613c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 107713c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 107813c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 107913c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 108013c78e4dSTobias Grosser 108113c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1082aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 108313c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 108413c78e4dSTobias Grosser 1085b06ff457STobias Grosser Value *HostPtr; 1086b06ff457STobias Grosser 1087b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1088b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1089b06ff457STobias Grosser else 1090b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 109113c78e4dSTobias Grosser 1092aaabbbf8STobias Grosser if (Offset) { 1093aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1094aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1095aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1096aaabbbf8STobias Grosser } 1097aaabbbf8STobias Grosser 109813c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 109913c78e4dSTobias Grosser 1100aaabbbf8STobias Grosser if (Offset) { 1101aaabbbf8STobias Grosser Size = Builder.CreateSub( 1102ff40087aSTobias Grosser Size, Builder.CreateMul( 1103ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1104aaabbbf8STobias Grosser } 1105aaabbbf8STobias Grosser 110613c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 110713c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 110813c78e4dSTobias Grosser else 110913c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 111013c78e4dSTobias Grosser 111113c78e4dSTobias Grosser isl_id_free(Id); 111213c78e4dSTobias Grosser isl_ast_expr_free(Arg); 111313c78e4dSTobias Grosser isl_ast_expr_free(Expr); 111413c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 111513c78e4dSTobias Grosser } 111613c78e4dSTobias Grosser 11171fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 111832837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 111932837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 112032837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 112132837fe3STobias Grosser isl_id_free(Id); 112232837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 112332837fe3STobias Grosser 112432837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 112532837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 112632837fe3STobias Grosser createKernel(UserStmt); 112732837fe3STobias Grosser isl_ast_expr_free(Expr); 112832837fe3STobias Grosser return; 112932837fe3STobias Grosser } 113032837fe3STobias Grosser 113113c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1132abed4969SSiddharth Bhat if (!ManagedMemory) 113313c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1134abed4969SSiddharth Bhat else 1135abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1136abed4969SSiddharth Bhat 113732837fe3STobias Grosser isl_ast_expr_free(Expr); 113813c78e4dSTobias Grosser return; 113913c78e4dSTobias Grosser } 114013c78e4dSTobias Grosser 114113c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1142abed4969SSiddharth Bhat if (!ManagedMemory) { 114313c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1144abed4969SSiddharth Bhat } else { 1145abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1146abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1147abed4969SSiddharth Bhat } 114813c78e4dSTobias Grosser isl_ast_expr_free(Expr); 114938fc0aedSTobias Grosser return; 115038fc0aedSTobias Grosser } 115138fc0aedSTobias Grosser 11525260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 11535260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 11545260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 11555260c041STobias Grosser isl_id_free(Anno); 11565260c041STobias Grosser 11575260c041STobias Grosser switch (KernelStmt->type) { 11585260c041STobias Grosser case ppcg_kernel_domain: 1159edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 11605260c041STobias Grosser isl_ast_node_free(UserStmt); 11615260c041STobias Grosser return; 11625260c041STobias Grosser case ppcg_kernel_copy: 1163b513b491STobias Grosser createKernelCopy(KernelStmt); 11645260c041STobias Grosser isl_ast_expr_free(Expr); 11655260c041STobias Grosser isl_ast_node_free(UserStmt); 11665260c041STobias Grosser return; 11675260c041STobias Grosser case ppcg_kernel_sync: 11685260c041STobias Grosser createKernelSync(); 11695260c041STobias Grosser isl_ast_expr_free(Expr); 11705260c041STobias Grosser isl_ast_node_free(UserStmt); 11715260c041STobias Grosser return; 11725260c041STobias Grosser } 11735260c041STobias Grosser 11745260c041STobias Grosser isl_ast_expr_free(Expr); 11755260c041STobias Grosser isl_ast_node_free(UserStmt); 11765260c041STobias Grosser return; 11775260c041STobias Grosser } 1178b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1179b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1180b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1181b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1182b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1183b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1184b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1185b513b491STobias Grosser 1186b513b491STobias Grosser if (KernelStmt->u.c.read) { 1187b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1188b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1189b513b491STobias Grosser } else { 1190b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1191b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1192b513b491STobias Grosser } 1193b513b491STobias Grosser } 11945260c041STobias Grosser 1195edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1196edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1197edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1198edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1199edb885cbSTobias Grosser 1200edb885cbSTobias Grosser LoopToScevMapT LTS; 1201edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1202edb885cbSTobias Grosser 1203edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1204edb885cbSTobias Grosser 1205edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1206edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1207edb885cbSTobias Grosser else 1208a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1209edb885cbSTobias Grosser } 1210edb885cbSTobias Grosser 12115260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 12125260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 121317f01968SSiddharth Bhat 121417f01968SSiddharth Bhat Function *Sync; 121517f01968SSiddharth Bhat 121617f01968SSiddharth Bhat switch (Arch) { 121717f01968SSiddharth Bhat case GPUArch::NVPTX64: 121817f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 121917f01968SSiddharth Bhat break; 122017f01968SSiddharth Bhat } 122117f01968SSiddharth Bhat 12225260c041STobias Grosser Builder.CreateCall(Sync, {}); 12235260c041STobias Grosser } 12245260c041STobias Grosser 1225edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1226edb885cbSTobias Grosser /// 1227edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1228edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1229edb885cbSTobias Grosser /// 1230edb885cbSTobias Grosser /// @param Node The node to collect references for. 1231edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1232edb885cbSTobias Grosser /// 1233edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1234edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1235edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1236edb885cbSTobias Grosser return isl_bool_true; 1237edb885cbSTobias Grosser 1238edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1239edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1240edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1241edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1242edb885cbSTobias Grosser isl_id_free(Id); 1243edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1244edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1245edb885cbSTobias Grosser 1246edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1247edb885cbSTobias Grosser return isl_bool_true; 1248edb885cbSTobias Grosser 1249edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1250edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1251edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1252edb885cbSTobias Grosser isl_id_free(Id); 1253edb885cbSTobias Grosser 125400bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1255edb885cbSTobias Grosser 1256edb885cbSTobias Grosser return isl_bool_true; 1257edb885cbSTobias Grosser } 1258edb885cbSTobias Grosser 1259f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 1260f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) { 1261f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1262f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 1263f291c8d5SSiddharth Bhat // all variants of the intrinsic "llvm.sqrt.*" 1264f291c8d5SSiddharth Bhat return F->isIntrinsic() && F->getName().startswith("llvm.sqrt"); 1265f291c8d5SSiddharth Bhat } 1266f291c8d5SSiddharth Bhat 1267f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1268f291c8d5SSiddharth Bhat /// 1269f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1270f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1271f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1272f291c8d5SSiddharth Bhat /// `Function`s. 1273f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1274f291c8d5SSiddharth Bhat 1275f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1276f291c8d5SSiddharth Bhat static SetVector<Function *> 1277f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1278f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1279f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1280f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1281f291c8d5SSiddharth Bhat if (F) { 1282f291c8d5SSiddharth Bhat assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1283f291c8d5SSiddharth Bhat "this point if an invalid function " 1284f291c8d5SSiddharth Bhat "were present in a kernel."); 1285f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1286f291c8d5SSiddharth Bhat } 1287f291c8d5SSiddharth Bhat } 1288f291c8d5SSiddharth Bhat return SubtreeFunctions; 1289f291c8d5SSiddharth Bhat } 1290f291c8d5SSiddharth Bhat 1291f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 1292f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1293edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1294edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1295edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1296edb885cbSTobias Grosser SubtreeReferences References = { 1297edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1298edb885cbSTobias Grosser 1299edb885cbSTobias Grosser for (const auto &I : IDToValue) 1300edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1301edb885cbSTobias Grosser 1302edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1303edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1304edb885cbSTobias Grosser 1305edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1306edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1307edb885cbSTobias Grosser 1308edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1309d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1310edb885cbSTobias Grosser 1311edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1312edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1313edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1314edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1315edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1316edb885cbSTobias Grosser SubtreeValues.remove(Val); 1317edb885cbSTobias Grosser isl_id_free(Id); 1318edb885cbSTobias Grosser } 1319edb885cbSTobias Grosser isl_space_free(Space); 1320edb885cbSTobias Grosser 1321edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1322edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1323edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1324edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1325edb885cbSTobias Grosser SubtreeValues.remove(Val); 1326edb885cbSTobias Grosser isl_id_free(Id); 1327edb885cbSTobias Grosser } 1328edb885cbSTobias Grosser 1329f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1330f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1331f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1332f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1333f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1334f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1335f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1336f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1337f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 1338f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 1339f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SubtreeValues)); 1340f291c8d5SSiddharth Bhat 1341f291c8d5SSiddharth Bhat return std::make_pair(ValidSubtreeValues, ValidSubtreeFunctions); 1342edb885cbSTobias Grosser } 1343edb885cbSTobias Grosser 134474dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 134574dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 134674dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 134774dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 134874dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 134974dc3cb4STobias Grosser 135074dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 135174dc3cb4STobias Grosser DT.eraseNode(BB); 135274dc3cb4STobias Grosser } 135374dc3cb4STobias Grosser 135474dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 135574dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 135674dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 135774dc3cb4STobias Grosser if (L) 135874dc3cb4STobias Grosser SE.forgetLoop(L); 135974dc3cb4STobias Grosser } 136074dc3cb4STobias Grosser } 136174dc3cb4STobias Grosser 136274dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 136374dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 136474dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 136574dc3cb4STobias Grosser if (L) 136674dc3cb4STobias Grosser SE.forgetLoop(L); 136774dc3cb4STobias Grosser LI.removeBlock(&BB); 136874dc3cb4STobias Grosser } 136974dc3cb4STobias Grosser } 137074dc3cb4STobias Grosser 137179a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 137279a947c2STobias Grosser std::vector<Value *> Sizes; 137379a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 137479a947c2STobias Grosser 137579a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 137679a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 137779a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 137879a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 137979a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 138079a947c2STobias Grosser Sizes.push_back(Res); 138179a947c2STobias Grosser } 138279a947c2STobias Grosser isl_ast_build_free(Context); 138379a947c2STobias Grosser 138479a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 138579a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 138679a947c2STobias Grosser 138779a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 138879a947c2STobias Grosser } 138979a947c2STobias Grosser 139079a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 139179a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 139279a947c2STobias Grosser std::vector<Value *> Sizes; 139379a947c2STobias Grosser 139479a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 139579a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 139679a947c2STobias Grosser Sizes.push_back(Res); 139779a947c2STobias Grosser } 139879a947c2STobias Grosser 139979a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 140079a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 140179a947c2STobias Grosser 140279a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 140379a947c2STobias Grosser } 140479a947c2STobias Grosser 1405a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1406a90be207SSiddharth Bhat Instruction *Param, int Index) { 1407a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1408a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1409a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1410a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1411a90be207SSiddharth Bhat } 1412a90be207SSiddharth Bhat 141357693272STobias Grosser Value * 141457693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 141557693272STobias Grosser SetVector<Value *> SubtreeValues) { 1416a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1417a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1418a90be207SSiddharth Bhat 1419a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 142079a947c2STobias Grosser 142179a947c2STobias Grosser BasicBlock *EntryBlock = 142279a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 142367726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 142479a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 142567726b32STobias Grosser Instruction *Parameters = new AllocaInst( 142667726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 142779a947c2STobias Grosser 142879a947c2STobias Grosser int Index = 0; 142979a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 143079a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 143179a947c2STobias Grosser continue; 143279a947c2STobias Grosser 143379a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 143479a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 143579a947c2STobias Grosser 1436a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1437a90be207SSiddharth Bhat 1438abed4969SSiddharth Bhat Value *DevArray = nullptr; 1439abed4969SSiddharth Bhat if (ManagedMemory) { 1440abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1441abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1442abed4969SSiddharth Bhat } else { 1443abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 144479a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1445abed4969SSiddharth Bhat } 1446abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1447abed4969SSiddharth Bhat "initialized"); 1448aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1449aaabbbf8STobias Grosser 1450aaabbbf8STobias Grosser if (Offset) { 1451aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1452aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1453aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1454aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1455aaabbbf8STobias Grosser } 1456fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1457fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1458aaabbbf8STobias Grosser 1459fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1460abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1461abed4969SSiddharth Bhat if (ManagedMemory) 1462abed4969SSiddharth Bhat ValPtr = DevArray; 1463abed4969SSiddharth Bhat else 1464abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1465abed4969SSiddharth Bhat 1466abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1467abed4969SSiddharth Bhat " to be stored into Parameters"); 1468fe74a7a1STobias Grosser Value *ValPtrCast = 1469fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1470fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1471fe74a7a1STobias Grosser } else { 147267726b32STobias Grosser Instruction *Param = 147367726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 147467726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 147579a947c2STobias Grosser EntryBlock->getTerminator()); 147679a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 147779a947c2STobias Grosser Value *ParamTyped = 147879a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 147979a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1480fe74a7a1STobias Grosser } 148179a947c2STobias Grosser Index++; 148279a947c2STobias Grosser } 148379a947c2STobias Grosser 1484a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1485a490147cSTobias Grosser 1486a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1487a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1488a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1489a490147cSTobias Grosser isl_id_free(Id); 1490a90be207SSiddharth Bhat 1491a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1492a90be207SSiddharth Bhat 149367726b32STobias Grosser Instruction *Param = 149467726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 149567726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1496a490147cSTobias Grosser EntryBlock->getTerminator()); 1497a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1498a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1499a490147cSTobias Grosser Index++; 1500a490147cSTobias Grosser } 1501a490147cSTobias Grosser 1502d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1503d8b94bcaSTobias Grosser 1504d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1505d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1506d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1507d8b94bcaSTobias Grosser isl_id_free(Id); 1508a90be207SSiddharth Bhat 1509a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1510a90be207SSiddharth Bhat 151167726b32STobias Grosser Instruction *Param = 151267726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 151367726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1514d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1515d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1516a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1517d8b94bcaSTobias Grosser Index++; 1518d8b94bcaSTobias Grosser } 1519d8b94bcaSTobias Grosser 152057693272STobias Grosser for (auto Val : SubtreeValues) { 1521a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1522a90be207SSiddharth Bhat 152367726b32STobias Grosser Instruction *Param = 152467726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 152567726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 152657693272STobias Grosser EntryBlock->getTerminator()); 152757693272STobias Grosser Builder.CreateStore(Val, Param); 1528a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1529a90be207SSiddharth Bhat Index++; 1530a90be207SSiddharth Bhat } 1531a90be207SSiddharth Bhat 1532a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1533a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1534a90be207SSiddharth Bhat Instruction *Param = 1535a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1536a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1537a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1538a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1539a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 154057693272STobias Grosser Index++; 154157693272STobias Grosser } 154257693272STobias Grosser 154379a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 154479a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 154579a947c2STobias Grosser Launch + "_params_i8ptr", Location); 154679a947c2STobias Grosser } 154779a947c2STobias Grosser 1548f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1549f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1550f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1551f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1552f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1553f291c8d5SSiddharth Bhat if (!Clone) 1554f291c8d5SSiddharth Bhat Clone = 1555f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1556f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1557f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1558f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1559f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1560f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1561f291c8d5SSiddharth Bhat } 1562f291c8d5SSiddharth Bhat } 156332837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 156432837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 156532837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 156632837fe3STobias Grosser isl_id_free(Id); 156732837fe3STobias Grosser isl_ast_node_free(KernelStmt); 156832837fe3STobias Grosser 1569bc653f20STobias Grosser if (Kernel->n_grid > 1) 1570bc653f20STobias Grosser DeepestParallel = 1571bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1572bc653f20STobias Grosser else 1573bc653f20STobias Grosser DeepestSequential = 1574bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1575bc653f20STobias Grosser 1576c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1577c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1578c1c6a2a6STobias Grosser 1579f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1580f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1581f291c8d5SSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1582edb885cbSTobias Grosser 158332837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 158432837fe3STobias Grosser 158532837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1586472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1587edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1588587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1589b06ff457STobias Grosser ScalarMap.clear(); 159032837fe3STobias Grosser 1591edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1592edb885cbSTobias Grosser 1593edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1594edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1595edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1596edb885cbSTobias Grosser for (const Loop *L : Loops) { 1597edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1598edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1599edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1600edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1601edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1602edb885cbSTobias Grosser SubtreeValues.insert(V); 1603edb885cbSTobias Grosser } 1604edb885cbSTobias Grosser 1605f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1606f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 160732837fe3STobias Grosser 160859ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 160959ab0705STobias Grosser 161051dfc275STobias Grosser finalizeKernelArguments(Kernel); 161174dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 1612c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 161374dc3cb4STobias Grosser clearDominators(F); 161474dc3cb4STobias Grosser clearScalarEvolution(F); 161574dc3cb4STobias Grosser clearLoops(F); 161674dc3cb4STobias Grosser 1617472f9654STobias Grosser IDToValue = HostIDs; 161832837fe3STobias Grosser 1619b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1620b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1621edb885cbSTobias Grosser EscapeMap.clear(); 1622edb885cbSTobias Grosser IDToSAI.clear(); 162374dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 162474dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 16254d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 162674dc3cb4STobias Grosser LocalArrays.clear(); 1627edb885cbSTobias Grosser 162851dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 162951dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 163057693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 163179a947c2STobias Grosser 1632*79f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 163357793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 163457793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 163557793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 163679a947c2STobias Grosser 163779a947c2STobias Grosser Value *GridDimX, *GridDimY; 163879a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 163979a947c2STobias Grosser 164079a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 164179a947c2STobias Grosser BlockDimZ, Parameters); 164257793596STobias Grosser createCallFreeKernel(GPUKernel); 1643b513b491STobias Grosser 1644b513b491STobias Grosser for (auto Id : KernelIds) 1645b513b491STobias Grosser isl_id_free(Id); 1646b513b491STobias Grosser 1647b513b491STobias Grosser KernelIds.clear(); 164832837fe3STobias Grosser } 164932837fe3STobias Grosser 165032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 165132837fe3STobias Grosser /// 165232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 165332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1654d277fedaSSiddharth Bhat std::string Ret = ""; 165532837fe3STobias Grosser 1656d277fedaSSiddharth Bhat if (!is64Bit) { 1657d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1658d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1659d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1660d277fedaSSiddharth Bhat } else { 1661d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1662d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1663d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1664d277fedaSSiddharth Bhat } 166532837fe3STobias Grosser 166632837fe3STobias Grosser return Ret; 166732837fe3STobias Grosser } 166832837fe3STobias Grosser 1669edb885cbSTobias Grosser Function * 1670edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1671edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 167232837fe3STobias Grosser std::vector<Type *> Args; 1673*79f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 167432837fe3STobias Grosser 167532837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 167632837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 167732837fe3STobias Grosser continue; 167832837fe3STobias Grosser 1679fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1680fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1681fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1682fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 1683fe74a7a1STobias Grosser } else { 1684d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1685d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 168632837fe3STobias Grosser } 1687fe74a7a1STobias Grosser } 168832837fe3STobias Grosser 1689f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1690f6044bd0STobias Grosser 1691f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 1692f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 1693f6044bd0STobias Grosser 1694c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1695c84a1995STobias Grosser 1696cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1697cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1698cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1699cf66ef26STobias Grosser isl_id_free(Id); 1700cf66ef26STobias Grosser Args.push_back(Val->getType()); 1701cf66ef26STobias Grosser } 1702c84a1995STobias Grosser 1703edb885cbSTobias Grosser for (auto *V : SubtreeValues) 1704edb885cbSTobias Grosser Args.push_back(V->getType()); 1705edb885cbSTobias Grosser 170632837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 170732837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 170832837fe3STobias Grosser GPUModule.get()); 170917f01968SSiddharth Bhat 171017f01968SSiddharth Bhat switch (Arch) { 171117f01968SSiddharth Bhat case GPUArch::NVPTX64: 171232837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 171317f01968SSiddharth Bhat break; 171417f01968SSiddharth Bhat } 171532837fe3STobias Grosser 171632837fe3STobias Grosser auto Arg = FN->arg_begin(); 171732837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 171832837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 171932837fe3STobias Grosser continue; 172032837fe3STobias Grosser 1721edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1722edb885cbSTobias Grosser 1723edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1724edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1725edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1726edb885cbSTobias Grosser Value *Val = &*Arg; 1727edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1728edb885cbSTobias Grosser isl_ast_build *Build = 1729edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1730f5aff704SRoman Gareev Sizes.push_back(nullptr); 1731edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1732edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1733edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1734edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1735edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1736edb885cbSTobias Grosser } 1737edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 17384d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 173974dc3cb4STobias Grosser LocalArrays.push_back(Val); 1740edb885cbSTobias Grosser 1741edb885cbSTobias Grosser isl_ast_build_free(Build); 1742b513b491STobias Grosser KernelIds.push_back(Id); 1743edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 174432837fe3STobias Grosser Arg++; 174532837fe3STobias Grosser } 174632837fe3STobias Grosser 1747f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1748f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1749f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1750f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1751f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1752f6044bd0STobias Grosser Arg++; 1753f6044bd0STobias Grosser } 1754f6044bd0STobias Grosser 1755c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1756c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1757c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 175812453403STobias Grosser Value *Val = IDToValue[Id]; 175912453403STobias Grosser ValueMap[Val] = &*Arg; 1760c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1761c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1762c84a1995STobias Grosser Arg++; 1763c84a1995STobias Grosser } 1764c84a1995STobias Grosser 1765edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1766edb885cbSTobias Grosser Arg->setName(V->getName()); 1767edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1768edb885cbSTobias Grosser Arg++; 1769edb885cbSTobias Grosser } 1770edb885cbSTobias Grosser 177132837fe3STobias Grosser return FN; 177232837fe3STobias Grosser } 177332837fe3STobias Grosser 1774472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 177517f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 177617f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1777472f9654STobias Grosser 177817f01968SSiddharth Bhat switch (Arch) { 177917f01968SSiddharth Bhat case GPUArch::NVPTX64: 178017f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 178117f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 178217f01968SSiddharth Bhat 178317f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 178417f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 178517f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 178617f01968SSiddharth Bhat break; 178717f01968SSiddharth Bhat } 1788472f9654STobias Grosser 1789472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1790472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1791472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1792472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1793472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1794472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1795472f9654STobias Grosser IDToValue[Id] = Val; 1796472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1797472f9654STobias Grosser }; 1798472f9654STobias Grosser 1799472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1800472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1801472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1802472f9654STobias Grosser } 1803472f9654STobias Grosser 1804472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1805472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1806472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1807472f9654STobias Grosser } 1808472f9654STobias Grosser } 1809472f9654STobias Grosser 181000bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 181100bb5a99STobias Grosser auto Arg = FN->arg_begin(); 181200bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 181300bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 181400bb5a99STobias Grosser continue; 181500bb5a99STobias Grosser 181600bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 181700bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 181800bb5a99STobias Grosser isl_id_free(Id); 181900bb5a99STobias Grosser 182000bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 182100bb5a99STobias Grosser Arg++; 182200bb5a99STobias Grosser continue; 182300bb5a99STobias Grosser } 182400bb5a99STobias Grosser 1825fe74a7a1STobias Grosser Value *Val = &*Arg; 1826fe74a7a1STobias Grosser 1827fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 182800bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 1829fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1830fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 1831fe74a7a1STobias Grosser } 1832fe74a7a1STobias Grosser 1833fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 183400bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 183500bb5a99STobias Grosser 183600bb5a99STobias Grosser Arg++; 183700bb5a99STobias Grosser } 183800bb5a99STobias Grosser } 183900bb5a99STobias Grosser 184051dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 184151dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 184251dfc275STobias Grosser auto Arg = FN->arg_begin(); 184351dfc275STobias Grosser 184451dfc275STobias Grosser bool StoredScalar = false; 184551dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 184651dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 184751dfc275STobias Grosser continue; 184851dfc275STobias Grosser 184951dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 185051dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 185151dfc275STobias Grosser isl_id_free(Id); 185251dfc275STobias Grosser 185351dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 185451dfc275STobias Grosser Arg++; 185551dfc275STobias Grosser continue; 185651dfc275STobias Grosser } 185751dfc275STobias Grosser 185851dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 185951dfc275STobias Grosser Arg++; 186051dfc275STobias Grosser continue; 186151dfc275STobias Grosser } 186251dfc275STobias Grosser 186351dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 186451dfc275STobias Grosser Value *ArgPtr = &*Arg; 186551dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 186651dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 186751dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 186851dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 186951dfc275STobias Grosser StoredScalar = true; 187051dfc275STobias Grosser 187151dfc275STobias Grosser Arg++; 187251dfc275STobias Grosser } 187351dfc275STobias Grosser 187451dfc275STobias Grosser if (StoredScalar) 187551dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 187651dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 187751dfc275STobias Grosser /// To support this case we need to store these scalars back at each 187851dfc275STobias Grosser /// memory store or at least before each kernel barrier. 187951dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 188051dfc275STobias Grosser BuildSuccessful = 0; 188151dfc275STobias Grosser } 188251dfc275STobias Grosser 1883b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1884b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1885b513b491STobias Grosser 1886b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 1887b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 1888b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1889b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1890b513b491STobias Grosser 1891f919d8b3STobias Grosser Type *ArrayTy = EleTy; 1892b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 1893b513b491STobias Grosser 1894f5aff704SRoman Gareev Sizes.push_back(nullptr); 1895928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1896b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1897f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 1898b513b491STobias Grosser isl_val_free(Val); 1899b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1900928d7573STobias Grosser } 1901928d7573STobias Grosser 1902928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 1903928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1904928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 1905928d7573STobias Grosser isl_val_free(Val); 1906b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 1907b513b491STobias Grosser } 1908b513b491STobias Grosser 1909130ca30fSTobias Grosser const ScopArrayInfo *SAI; 1910130ca30fSTobias Grosser Value *Allocation; 1911130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 1912130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 1913130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1914130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1915130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1916f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1917f919d8b3STobias Grosser 1918130ca30fSTobias Grosser Allocation = GlobalVar; 1919130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 1920130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1921130ca30fSTobias Grosser } else { 1922130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 1923130ca30fSTobias Grosser } 19244d5a9172STobias Grosser SAI = 19254d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1926b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1927130ca30fSTobias Grosser IDToValue[Id] = Allocation; 1928130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 1929b513b491STobias Grosser KernelIds.push_back(Id); 1930b513b491STobias Grosser IDToSAI[Id] = SAI; 1931b513b491STobias Grosser } 1932b513b491STobias Grosser } 1933b513b491STobias Grosser 1934f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 1935f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 1936f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 1937*79f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 193832837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 193917f01968SSiddharth Bhat 194017f01968SSiddharth Bhat switch (Arch) { 194117f01968SSiddharth Bhat case GPUArch::NVPTX64: 194217f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 194332837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 194417f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 194517f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 194632837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 194717f01968SSiddharth Bhat break; 194817f01968SSiddharth Bhat } 194932837fe3STobias Grosser 1950edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 195132837fe3STobias Grosser 195259ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 195332837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 195432837fe3STobias Grosser 195559ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 195659ab0705STobias Grosser 195732837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 195832837fe3STobias Grosser Builder.CreateRetVoid(); 195932837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1960472f9654STobias Grosser 1961629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 1962629109b6STobias Grosser 196300bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 1964b513b491STobias Grosser createKernelVariables(Kernel, FN); 1965472f9654STobias Grosser insertKernelIntrinsics(Kernel); 196632837fe3STobias Grosser } 196732837fe3STobias Grosser 196874dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 196917f01968SSiddharth Bhat llvm::Triple GPUTriple; 197017f01968SSiddharth Bhat 197117f01968SSiddharth Bhat switch (Arch) { 197217f01968SSiddharth Bhat case GPUArch::NVPTX64: 197317f01968SSiddharth Bhat switch (Runtime) { 197417f01968SSiddharth Bhat case GPURuntime::CUDA: 197517f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 197617f01968SSiddharth Bhat break; 197717f01968SSiddharth Bhat case GPURuntime::OpenCL: 197817f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 197917f01968SSiddharth Bhat break; 198017f01968SSiddharth Bhat } 198117f01968SSiddharth Bhat break; 198217f01968SSiddharth Bhat } 198317f01968SSiddharth Bhat 198474dc3cb4STobias Grosser std::string ErrMsg; 198574dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 198674dc3cb4STobias Grosser 198774dc3cb4STobias Grosser if (!GPUTarget) { 198874dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 198974dc3cb4STobias Grosser return ""; 199074dc3cb4STobias Grosser } 199174dc3cb4STobias Grosser 199274dc3cb4STobias Grosser TargetOptions Options; 199374dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 199417f01968SSiddharth Bhat 199517f01968SSiddharth Bhat std::string subtarget; 199617f01968SSiddharth Bhat 199717f01968SSiddharth Bhat switch (Arch) { 199817f01968SSiddharth Bhat case GPUArch::NVPTX64: 199917f01968SSiddharth Bhat subtarget = CudaVersion; 200017f01968SSiddharth Bhat break; 200117f01968SSiddharth Bhat } 200217f01968SSiddharth Bhat 200317f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 200417f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 200574dc3cb4STobias Grosser 200674dc3cb4STobias Grosser SmallString<0> ASMString; 200774dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 200874dc3cb4STobias Grosser llvm::legacy::PassManager PM; 200974dc3cb4STobias Grosser 201074dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 201174dc3cb4STobias Grosser 201274dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 201374dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 201474dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 201574dc3cb4STobias Grosser return ""; 201674dc3cb4STobias Grosser } 201774dc3cb4STobias Grosser 201874dc3cb4STobias Grosser PM.run(*GPUModule); 201974dc3cb4STobias Grosser 202074dc3cb4STobias Grosser return ASMStream.str(); 202174dc3cb4STobias Grosser } 202274dc3cb4STobias Grosser 202357793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 202465d7f72fSSiddharth Bhat 20255857b701STobias Grosser if (verifyModule(*GPUModule)) { 202665d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 202765d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 202865d7f72fSSiddharth Bhat 202965d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 203065d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 203165d7f72fSSiddharth Bhat 20325857b701STobias Grosser BuildSuccessful = false; 20335857b701STobias Grosser return ""; 20345857b701STobias Grosser } 203532837fe3STobias Grosser 203632837fe3STobias Grosser if (DumpKernelIR) 203732837fe3STobias Grosser outs() << *GPUModule << "\n"; 203832837fe3STobias Grosser 20399a18d559STobias Grosser // Optimize module. 20409a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 20419a18d559STobias Grosser PassManagerBuilder PassBuilder; 20429a18d559STobias Grosser PassBuilder.OptLevel = 3; 20439a18d559STobias Grosser PassBuilder.SizeLevel = 0; 20449a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 20459a18d559STobias Grosser OptPasses.run(*GPUModule); 20469a18d559STobias Grosser 204774dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 204874dc3cb4STobias Grosser 204974dc3cb4STobias Grosser if (DumpKernelASM) 205074dc3cb4STobias Grosser outs() << Assembly << "\n"; 205174dc3cb4STobias Grosser 205232837fe3STobias Grosser GPUModule.release(); 2053472f9654STobias Grosser KernelIDs.clear(); 205457793596STobias Grosser 205557793596STobias Grosser return Assembly; 205632837fe3STobias Grosser } 205732837fe3STobias Grosser 20589dfe4e7cSTobias Grosser namespace { 20599dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 20609dfe4e7cSTobias Grosser public: 20619dfe4e7cSTobias Grosser static char ID; 20629dfe4e7cSTobias Grosser 206317f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 206417f01968SSiddharth Bhat 206517f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 206617f01968SSiddharth Bhat 2067e938517eSTobias Grosser /// The scop that is currently processed. 2068e938517eSTobias Grosser Scop *S; 2069e938517eSTobias Grosser 207038fc0aedSTobias Grosser LoopInfo *LI; 207138fc0aedSTobias Grosser DominatorTree *DT; 207238fc0aedSTobias Grosser ScalarEvolution *SE; 207338fc0aedSTobias Grosser const DataLayout *DL; 207438fc0aedSTobias Grosser RegionInfo *RI; 207538fc0aedSTobias Grosser 20769dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 20779dfe4e7cSTobias Grosser 2078e938517eSTobias Grosser /// Construct compilation options for PPCG. 2079e938517eSTobias Grosser /// 2080e938517eSTobias Grosser /// @returns The compilation options. 2081e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2082e938517eSTobias Grosser auto DebugOptions = 2083e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2084e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2085e938517eSTobias Grosser 2086e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2087e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2088e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2089e938517eSTobias Grosser DebugOptions->dump_sizes = false; 20908950ceadSTobias Grosser DebugOptions->verbose = false; 2091e938517eSTobias Grosser 2092e938517eSTobias Grosser Options->debug = DebugOptions; 2093e938517eSTobias Grosser 2094e938517eSTobias Grosser Options->reschedule = true; 2095e938517eSTobias Grosser Options->scale_tile_loops = false; 2096e938517eSTobias Grosser Options->wrap = false; 2097e938517eSTobias Grosser 2098e938517eSTobias Grosser Options->non_negative_parameters = false; 2099e938517eSTobias Grosser Options->ctx = nullptr; 2100e938517eSTobias Grosser Options->sizes = nullptr; 2101e938517eSTobias Grosser 21024eaedde5STobias Grosser Options->tile_size = 32; 21034eaedde5STobias Grosser 2104130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2105b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2106b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2107e938517eSTobias Grosser 2108e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2109e938517eSTobias Grosser Options->openmp = false; 2110e938517eSTobias Grosser Options->linearize_device_arrays = true; 2111e938517eSTobias Grosser Options->live_range_reordering = false; 2112e938517eSTobias Grosser 2113e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2114e938517eSTobias Grosser Options->opencl_use_gpu = false; 2115e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2116e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2117e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2118e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2119e938517eSTobias Grosser 2120e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2121e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2122e938517eSTobias Grosser 2123e938517eSTobias Grosser return Options; 2124e938517eSTobias Grosser } 2125e938517eSTobias Grosser 2126f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2127f384594dSTobias Grosser /// 2128f384594dSTobias Grosser /// Instead of a normal access of the form: 2129f384594dSTobias Grosser /// 2130f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2131f384594dSTobias Grosser /// 2132f384594dSTobias Grosser /// a tagged access has the form 2133f384594dSTobias Grosser /// 2134f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2135f384594dSTobias Grosser /// 2136f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2137f384594dSTobias Grosser /// triggered the access. 2138f384594dSTobias Grosser /// 2139f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2140f384594dSTobias Grosser /// 2141f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2142f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2143f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2144f384594dSTobias Grosser 2145f384594dSTobias Grosser for (auto &Stmt : *S) 2146f384594dSTobias Grosser for (auto &Acc : Stmt) 2147f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 2148f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 2149f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2150f384594dSTobias Grosser 2151f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2152f384594dSTobias Grosser Space = isl_space_range(Space); 2153f384594dSTobias Grosser Space = isl_space_from_range(Space); 21546293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2155f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2156f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2157f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2158f384594dSTobias Grosser } 2159f384594dSTobias Grosser 2160f384594dSTobias Grosser return Accesses; 2161f384594dSTobias Grosser } 2162f384594dSTobias Grosser 2163f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2164f384594dSTobias Grosser /// 2165f384594dSTobias Grosser /// @see getTaggedAccesses 2166f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2167f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2168f384594dSTobias Grosser } 2169f384594dSTobias Grosser 2170f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2171f384594dSTobias Grosser /// 2172f384594dSTobias Grosser /// @see getTaggedAccesses 2173f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2174f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2175f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2176f384594dSTobias Grosser } 2177f384594dSTobias Grosser 2178f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2179f384594dSTobias Grosser /// 2180f384594dSTobias Grosser /// @see getTaggedAccesses 2181f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2182f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2183f384594dSTobias Grosser } 2184f384594dSTobias Grosser 2185aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2186aef5196fSTobias Grosser /// 2187aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2188aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2189aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2190aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2191aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2192aef5196fSTobias Grosser /// the data format that ppcg expects. 2193aef5196fSTobias Grosser /// 2194aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2195aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2196aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2197bd81a7eeSTobias Grosser S->getIslCtx(), 2198bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2199aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2200aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 2201aef5196fSTobias Grosser 2202aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2203aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2204aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2205aef5196fSTobias Grosser } 2206aef5196fSTobias Grosser 2207aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 2208d7754a12SRoman Gareev auto Id = Array->getBasePtrId(); 2209aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2210aef5196fSTobias Grosser } 2211aef5196fSTobias Grosser 2212aef5196fSTobias Grosser isl_space_free(Space); 2213aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2214aef5196fSTobias Grosser 2215aef5196fSTobias Grosser return Names; 2216aef5196fSTobias Grosser } 2217aef5196fSTobias Grosser 2218e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2219e938517eSTobias Grosser /// 2220f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2221f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2222f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2223f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2224e938517eSTobias Grosser /// 2225e938517eSTobias Grosser /// @returns A new ppcg scop. 2226e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 2227e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2228e938517eSTobias Grosser 2229e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2230a82f2d26SSiddharth Bhat // enable live range reordering 2231a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2232e938517eSTobias Grosser 2233e938517eSTobias Grosser PPCGScop->start = 0; 2234e938517eSTobias Grosser PPCGScop->end = 0; 2235e938517eSTobias Grosser 2236f384594dSTobias Grosser PPCGScop->context = S->getContext(); 2237f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 2238e938517eSTobias Grosser PPCGScop->call = nullptr; 2239f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 2240f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 2241e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2242f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2243f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 2244f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2245f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 2246e938517eSTobias Grosser PPCGScop->live_out = nullptr; 2247e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2248a82f2d26SSiddharth Bhat PPCGScop->independence = 2249a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2250e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2251e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2252e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2253e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2254e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2255e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2256e938517eSTobias Grosser 2257f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2258e938517eSTobias Grosser 2259a82f2d26SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2260a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2261a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2262a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2263a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2264a82f2d26SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2265a82f2d26SSiddharth Bhat 2266a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2267e938517eSTobias Grosser PPCGScop->pet = nullptr; 2268e938517eSTobias Grosser 2269f384594dSTobias Grosser compute_tagger(PPCGScop); 2270f384594dSTobias Grosser compute_dependences(PPCGScop); 2271f384594dSTobias Grosser 2272e938517eSTobias Grosser return PPCGScop; 2273e938517eSTobias Grosser } 2274e938517eSTobias Grosser 2275a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 227660f63b49STobias Grosser /// 227760f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 227860f63b49STobias Grosser /// 227960f63b49STobias Grosser /// @returns A list of array accesses. 228060f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 228160f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 228260f63b49STobias Grosser 228360f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 228460f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 228560f63b49STobias Grosser Access->read = Acc->isRead(); 228660f63b49STobias Grosser Access->write = Acc->isWrite(); 228760f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 228860f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 228960f63b49STobias Grosser Space = isl_space_range(Space); 229060f63b49STobias Grosser Space = isl_space_from_range(Space); 22916293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 229260f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 229360f63b49STobias Grosser Access->tagged_access = 229460f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2295b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 229660f63b49STobias Grosser Access->ref_id = Acc->getId(); 229760f63b49STobias Grosser Access->next = Accesses; 2298b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 229960f63b49STobias Grosser Accesses = Access; 230060f63b49STobias Grosser } 230160f63b49STobias Grosser 230260f63b49STobias Grosser return Accesses; 230360f63b49STobias Grosser } 230460f63b49STobias Grosser 230569b46751STobias Grosser /// Collect the list of GPU statements. 230669b46751STobias Grosser /// 230769b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 230869b46751STobias Grosser /// as well as a list with all memory accesses. 230969b46751STobias Grosser /// 231069b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 231169b46751STobias Grosser /// 231269b46751STobias Grosser /// @returns A linked-list of statements. 231369b46751STobias Grosser gpu_stmt *getStatements() { 231469b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 231569b46751STobias Grosser std::distance(S->begin(), S->end())); 231669b46751STobias Grosser 231769b46751STobias Grosser int i = 0; 231869b46751STobias Grosser for (auto &Stmt : *S) { 231969b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 232069b46751STobias Grosser 232169b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 232269b46751STobias Grosser 232369b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 232469b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 232560f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 232669b46751STobias Grosser i++; 232769b46751STobias Grosser } 232869b46751STobias Grosser 232969b46751STobias Grosser return Stmts; 233069b46751STobias Grosser } 233169b46751STobias Grosser 233260f63b49STobias Grosser /// Derive the extent of an array. 233360f63b49STobias Grosser /// 2334d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2335d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2336d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2337d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2338d58acf86STobias Grosser /// subscript value for the first dimension. 233960f63b49STobias Grosser /// 234060f63b49STobias Grosser /// @param Array The array to derive the extent for. 234160f63b49STobias Grosser /// 234260f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 234360f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2344d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 234560f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 234660f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2347d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 234860f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2349d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2350d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2351d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2352d58acf86STobias Grosser 2353d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2354d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2355d58acf86STobias Grosser return isl_set_empty(Array->getSpace()); 2356d58acf86STobias Grosser } 2357d58acf86STobias Grosser 2358d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2359d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2360d58acf86STobias Grosser return isl_set_universe(Array->getSpace()); 2361d58acf86STobias Grosser } 2362d58acf86STobias Grosser 236360f63b49STobias Grosser isl_set *AccessSet = 236460f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 236560f63b49STobias Grosser 2366d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2367d58acf86STobias Grosser isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2368d58acf86STobias Grosser 2369d58acf86STobias Grosser isl_pw_aff *Val = 2370d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2371d58acf86STobias Grosser 2372d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2373d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2374d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2375d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2376d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2377d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2378d58acf86STobias Grosser OuterMin = 2379d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2380d58acf86STobias Grosser OuterMax = 2381d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2382d58acf86STobias Grosser 2383d58acf86STobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace()); 2384d58acf86STobias Grosser 2385d58acf86STobias Grosser Extent = isl_set_intersect( 2386d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2387d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2388d58acf86STobias Grosser 2389d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2390d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2391d58acf86STobias Grosser 2392b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2393d58acf86STobias Grosser isl_pw_aff *PwAff = 2394d58acf86STobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2395b7f68b8cSSiddharth Bhat 2396b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2397b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2398b7f68b8cSSiddharth Bhat if (!PwAff) { 2399b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2400b7f68b8cSSiddharth Bhat continue; 2401b7f68b8cSSiddharth Bhat } 2402b7f68b8cSSiddharth Bhat 2403d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2404d58acf86STobias Grosser isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2405d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2406d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2407d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2408d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2409d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2410d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2411d58acf86STobias Grosser } 2412d58acf86STobias Grosser 2413d58acf86STobias Grosser return Extent; 241460f63b49STobias Grosser } 241560f63b49STobias Grosser 241660f63b49STobias Grosser /// Derive the bounds of an array. 241760f63b49STobias Grosser /// 241860f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 241960f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 242060f63b49STobias Grosser /// ScopArrayInfo. 242160f63b49STobias Grosser /// 242260f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 242360f63b49STobias Grosser /// @param Array The polly array from which to take the information. 242460f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 242560f63b49STobias Grosser if (PPCGArray.n_index > 0) { 242602293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 242702293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 242802293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 242902293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 243002293ed7STobias Grosser isl_set_free(Dom); 243102293ed7STobias Grosser isl_aff *Zero = isl_aff_zero_on_domain(LS); 243202293ed7STobias Grosser PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 243302293ed7STobias Grosser } else { 243460f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 243560f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 243660f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 243760f63b49STobias Grosser isl_set_free(Dom); 243860f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 243902293ed7STobias Grosser isl_local_space *LS = 244002293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 244160f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 244260f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 244360f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 244460f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 244560f63b49STobias Grosser PPCGArray.bound[0] = Bound; 244660f63b49STobias Grosser } 244702293ed7STobias Grosser } 244860f63b49STobias Grosser 244960f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 245060f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 245160f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 245260f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 245360f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 245460f63b49STobias Grosser PPCGArray.bound[i] = Bound; 245560f63b49STobias Grosser } 245660f63b49STobias Grosser } 245760f63b49STobias Grosser 245860f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 245960f63b49STobias Grosser /// 246060f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 246160f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 246260f63b49STobias Grosser int i = 0; 2463d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 246460f63b49STobias Grosser std::string TypeName; 246560f63b49STobias Grosser raw_string_ostream OS(TypeName); 246660f63b49STobias Grosser 246760f63b49STobias Grosser OS << *Array->getElementType(); 246860f63b49STobias Grosser TypeName = OS.str(); 246960f63b49STobias Grosser 247060f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 247160f63b49STobias Grosser 247260f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 247360f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 247460f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 247560f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 247660f63b49STobias Grosser PPCGArray.extent = nullptr; 247760f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 247860f63b49STobias Grosser PPCGArray.bound = 247960f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 248060f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 248160f63b49STobias Grosser PPCGArray.n_ref = 0; 248260f63b49STobias Grosser PPCGArray.refs = nullptr; 248360f63b49STobias Grosser PPCGArray.accessed = true; 2484fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2485fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 248660f63b49STobias Grosser PPCGArray.has_compound_element = false; 248760f63b49STobias Grosser PPCGArray.local = false; 248860f63b49STobias Grosser PPCGArray.declare_local = false; 248960f63b49STobias Grosser PPCGArray.global = false; 249060f63b49STobias Grosser PPCGArray.linearize = false; 249160f63b49STobias Grosser PPCGArray.dep_order = nullptr; 249213c78e4dSTobias Grosser PPCGArray.user = Array; 249360f63b49STobias Grosser 249460f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 24952d010dafSTobias Grosser i++; 2496b9fc860aSTobias Grosser 2497b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 249860f63b49STobias Grosser } 249960f63b49STobias Grosser } 250060f63b49STobias Grosser 250160f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 250260f63b49STobias Grosser /// 250360f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 250460f63b49STobias Grosser isl_union_map *getArrayIdentity() { 250560f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 250660f63b49STobias Grosser 2507d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 250860f63b49STobias Grosser isl_space *Space = Array->getSpace(); 250960f63b49STobias Grosser Space = isl_space_map_from_set(Space); 251060f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 251160f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 251260f63b49STobias Grosser } 251360f63b49STobias Grosser 251460f63b49STobias Grosser return Maps; 251560f63b49STobias Grosser } 251660f63b49STobias Grosser 2517e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2518e938517eSTobias Grosser /// 2519a6d48f59SMichael Kruse /// @returns A new gpu program description. 2520e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2521e938517eSTobias Grosser 2522e938517eSTobias Grosser if (!PPCGScop) 2523e938517eSTobias Grosser return nullptr; 2524e938517eSTobias Grosser 2525e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2526e938517eSTobias Grosser 2527e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2528e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2529aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 253060f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 253160f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 253260f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 253360f63b49STobias Grosser PPCGProg->tagged_must_kill = 253460f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 253560f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 253660f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 2537e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2538a82f2d26SSiddharth Bhat 2539a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2540a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2541a82f2d26SSiddharth Bhat // what the semantics of this is. 2542a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2543a82f2d26SSiddharth Bhat PPCGProg->array_order = 2544a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 254569b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 254669b46751STobias Grosser PPCGProg->stmts = getStatements(); 254760f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 254860f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 254960f63b49STobias Grosser PPCGProg->n_array); 255060f63b49STobias Grosser 255160f63b49STobias Grosser createArrays(PPCGProg); 2552e938517eSTobias Grosser 2553d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2554e938517eSTobias Grosser return PPCGProg; 2555e938517eSTobias Grosser } 2556e938517eSTobias Grosser 255769b46751STobias Grosser struct PrintGPUUserData { 255869b46751STobias Grosser struct cuda_info *CudaInfo; 255969b46751STobias Grosser struct gpu_prog *PPCGProg; 256069b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 256169b46751STobias Grosser }; 256269b46751STobias Grosser 256369b46751STobias Grosser /// Print a user statement node in the host code. 256469b46751STobias Grosser /// 256569b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 256669b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 256769b46751STobias Grosser /// host ast. 256869b46751STobias Grosser /// 256969b46751STobias Grosser /// @param P The printer to print to 257069b46751STobias Grosser /// @param Options The printing options to use 257169b46751STobias Grosser /// @param Node The node to print 257269b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 257369b46751STobias Grosser /// expected to be of type PrintGPUUserData. 257469b46751STobias Grosser /// 257569b46751STobias Grosser /// @returns A printer to which the output has been printed. 257669b46751STobias Grosser static __isl_give isl_printer * 257769b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 257869b46751STobias Grosser __isl_take isl_ast_print_options *Options, 257969b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 258069b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 258169b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 258269b46751STobias Grosser 258369b46751STobias Grosser if (Id) { 258420251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 258520251734STobias Grosser 258620251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 258720251734STobias Grosser // otherwise try to call pet functionality that is not available in 258820251734STobias Grosser // Polly. 258920251734STobias Grosser if (IsUser) { 259020251734STobias Grosser P = isl_printer_start_line(P); 259120251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 259220251734STobias Grosser P = isl_printer_end_line(P); 259320251734STobias Grosser isl_id_free(Id); 259420251734STobias Grosser isl_ast_print_options_free(Options); 259520251734STobias Grosser return P; 259620251734STobias Grosser } 259720251734STobias Grosser 259869b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 259969b46751STobias Grosser isl_id_free(Id); 260069b46751STobias Grosser Data->Kernels.push_back(Kernel); 260169b46751STobias Grosser } 260269b46751STobias Grosser 260369b46751STobias Grosser return print_host_user(P, Options, Node, User); 260469b46751STobias Grosser } 260569b46751STobias Grosser 260669b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 260769b46751STobias Grosser /// 260869b46751STobias Grosser /// @param Kernel The kernel to print 260969b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 261069b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 261169b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 261269b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 261369b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 261469b46751STobias Grosser char *String = isl_printer_get_str(P); 261569b46751STobias Grosser printf("%s\n", String); 261669b46751STobias Grosser free(String); 261769b46751STobias Grosser isl_printer_free(P); 261869b46751STobias Grosser } 261969b46751STobias Grosser 262069b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 262169b46751STobias Grosser /// 262269b46751STobias Grosser /// @param Tree An AST describing GPU code 262369b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 262469b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 262569b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 262669b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 262769b46751STobias Grosser 262869b46751STobias Grosser PrintGPUUserData Data; 262969b46751STobias Grosser Data.PPCGProg = PPCGProg; 263069b46751STobias Grosser 263169b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 263269b46751STobias Grosser Options = 263369b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 263469b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 263569b46751STobias Grosser char *String = isl_printer_get_str(P); 263669b46751STobias Grosser printf("# host\n"); 263769b46751STobias Grosser printf("%s\n", String); 263869b46751STobias Grosser free(String); 263969b46751STobias Grosser isl_printer_free(P); 264069b46751STobias Grosser 264169b46751STobias Grosser for (auto Kernel : Data.Kernels) { 264269b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 264369b46751STobias Grosser printKernel(Kernel); 264469b46751STobias Grosser } 264569b46751STobias Grosser } 264669b46751STobias Grosser 2647f384594dSTobias Grosser // Generate a GPU program using PPCG. 2648f384594dSTobias Grosser // 2649f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2650f384594dSTobias Grosser // 2651f384594dSTobias Grosser // 1) Compute new schedule for the program. 2652f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2653f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2654f384594dSTobias Grosser // 2655f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2656f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2657f384594dSTobias Grosser // strategy directly from this pass. 2658f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2659f384594dSTobias Grosser 2660f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2661f384594dSTobias Grosser 2662f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2663f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2664f384594dSTobias Grosser PPCGGen->print = nullptr; 2665f384594dSTobias Grosser PPCGGen->print_user = nullptr; 266660c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2667f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2668f384594dSTobias Grosser PPCGGen->tree = nullptr; 2669f384594dSTobias Grosser PPCGGen->types.n = 0; 2670f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2671f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2672f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2673f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2674f384594dSTobias Grosser 2675f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2676f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2677f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 26782341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2679f384594dSTobias Grosser 2680f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2681f384594dSTobias Grosser 2682aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2683aef5196fSTobias Grosser 268469b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2685aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 268669b46751STobias Grosser } else { 2687aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 268869b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 268969b46751STobias Grosser } 2690aef5196fSTobias Grosser 2691f384594dSTobias Grosser if (DumpSchedule) { 2692f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2693f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2694f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2695f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2696f384594dSTobias Grosser if (Schedule) 2697f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2698f384594dSTobias Grosser else 2699f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2700f384594dSTobias Grosser 2701f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2702f384594dSTobias Grosser isl_printer_free(P); 2703f384594dSTobias Grosser } 2704f384594dSTobias Grosser 270569b46751STobias Grosser if (DumpCode) { 270669b46751STobias Grosser printf("Code\n"); 270769b46751STobias Grosser printf("====\n"); 270869b46751STobias Grosser if (PPCGGen->tree) 270969b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 271069b46751STobias Grosser else 271169b46751STobias Grosser printf("No code generated\n"); 271269b46751STobias Grosser } 271369b46751STobias Grosser 2714f384594dSTobias Grosser isl_schedule_free(Schedule); 2715f384594dSTobias Grosser 2716f384594dSTobias Grosser return PPCGGen; 2717f384594dSTobias Grosser } 2718f384594dSTobias Grosser 2719f384594dSTobias Grosser /// Free gpu_gen structure. 2720f384594dSTobias Grosser /// 2721f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2722f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2723f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2724f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2725f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2726f384594dSTobias Grosser free(PPCGGen); 2727f384594dSTobias Grosser } 2728f384594dSTobias Grosser 2729b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2730b307ed4dSTobias Grosser /// 2731b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2732b307ed4dSTobias Grosser /// ourselves. 2733b307ed4dSTobias Grosser /// 2734b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2735b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2736b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2737b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2738b307ed4dSTobias Grosser free(PPCGScop->options); 2739b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2740b307ed4dSTobias Grosser } 2741b307ed4dSTobias Grosser 274282f2af35STobias Grosser /// Approximate the number of points in the set. 274382f2af35STobias Grosser /// 274482f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 274582f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 274682f2af35STobias Grosser /// 274782f2af35STobias Grosser /// @param Set The set to count. 274882f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 274982f2af35STobias Grosser /// expression. 275082f2af35STobias Grosser /// 275182f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 275282f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 275382f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 275482f2af35STobias Grosser 275582f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 275682f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 275782f2af35STobias Grosser 275882f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 275982f2af35STobias Grosser Space = isl_space_params(Space); 276082f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 276182f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 276282f2af35STobias Grosser 276382f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 276482f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 276582f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 276682f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 276782f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 276882f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 276982f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 277082f2af35STobias Grosser } 277182f2af35STobias Grosser 277282f2af35STobias Grosser isl_set_free(Set); 277382f2af35STobias Grosser isl_pw_aff_free(OneAff); 277482f2af35STobias Grosser 277582f2af35STobias Grosser return Expr; 277682f2af35STobias Grosser } 277782f2af35STobias Grosser 277882f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 277982f2af35STobias Grosser /// statement. 278082f2af35STobias Grosser /// 278182f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 278282f2af35STobias Grosser /// instructions. 278382f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 278482f2af35STobias Grosser /// expression. 278582f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 278682f2af35STobias Grosser /// by @p Stmt. 278782f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 278882f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 278982f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 279082f2af35STobias Grosser 279182f2af35STobias Grosser long InstCount = 0; 279282f2af35STobias Grosser 279382f2af35STobias Grosser if (Stmt.isBlockStmt()) { 279482f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 279582f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 279682f2af35STobias Grosser } else { 279782f2af35STobias Grosser auto *R = Stmt.getRegion(); 279882f2af35STobias Grosser 279982f2af35STobias Grosser for (auto *BB : R->blocks()) { 280082f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 280182f2af35STobias Grosser } 280282f2af35STobias Grosser } 280382f2af35STobias Grosser 280482f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 280582f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 280682f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 280782f2af35STobias Grosser } 280882f2af35STobias Grosser 280982f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 281082f2af35STobias Grosser /// 281182f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 281282f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 281382f2af35STobias Grosser /// expression. 281482f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 281582f2af35STobias Grosser /// in @p S. 281682f2af35STobias Grosser __isl_give isl_ast_expr * 281782f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 281882f2af35STobias Grosser isl_ast_expr *Instructions; 281982f2af35STobias Grosser 282082f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 282182f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 282282f2af35STobias Grosser 282382f2af35STobias Grosser for (ScopStmt &Stmt : S) { 282482f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 282582f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 282682f2af35STobias Grosser } 282782f2af35STobias Grosser return Instructions; 282882f2af35STobias Grosser } 282982f2af35STobias Grosser 283082f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 283182f2af35STobias Grosser /// 283282f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 283382f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 283482f2af35STobias Grosser /// expression. 283582f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 283682f2af35STobias Grosser /// compute and to FALSE, otherwise. 283782f2af35STobias Grosser __isl_give isl_ast_expr * 283882f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 283982f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 284082f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 284182f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 284282f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 284382f2af35STobias Grosser } 284482f2af35STobias Grosser 2845f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 2846f291c8d5SSiddharth Bhat /// kernels. 2847f291c8d5SSiddharth Bhat /// 2848f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 2849f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 2850f291c8d5SSiddharth Bhat bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) { 2851f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 2852f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 2853f291c8d5SSiddharth Bhat if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 2854f291c8d5SSiddharth Bhat continue; 2855f291c8d5SSiddharth Bhat } 2856f291c8d5SSiddharth Bhat 2857bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 2858bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 2859bccaea57SSiddharth Bhat if (!p) 2860bccaea57SSiddharth Bhat continue; 2861bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 2862bccaea57SSiddharth Bhat return true; 2863bccaea57SSiddharth Bhat } 2864f291c8d5SSiddharth Bhat } 2865bccaea57SSiddharth Bhat return false; 2866bccaea57SSiddharth Bhat } 2867bccaea57SSiddharth Bhat 2868f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 2869f291c8d5SSiddharth Bhat bool containsInvalidKernelFunction(const Scop &S) { 2870bccaea57SSiddharth Bhat for (auto &Stmt : S) { 2871bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 2872f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock())) 2873bccaea57SSiddharth Bhat return true; 2874bccaea57SSiddharth Bhat } else { 2875bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 2876bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 2877bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 2878f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(BB)) 2879bccaea57SSiddharth Bhat return true; 2880bccaea57SSiddharth Bhat } 2881bccaea57SSiddharth Bhat } 2882bccaea57SSiddharth Bhat return false; 2883bccaea57SSiddharth Bhat } 2884bccaea57SSiddharth Bhat 288538fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 288638fc0aedSTobias Grosser /// 288732837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 288832837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 288932837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 289038fc0aedSTobias Grosser ScopAnnotator Annotator; 289138fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 289238fc0aedSTobias Grosser 289338fc0aedSTobias Grosser Region *R = &S->getRegion(); 289438fc0aedSTobias Grosser 289538fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 289638fc0aedSTobias Grosser 289738fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 289838fc0aedSTobias Grosser 289938fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 290038fc0aedSTobias Grosser 290138fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 290238fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 290338fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 290438fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 290538fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 290638fc0aedSTobias Grosser // code generating this scop. 2907256070d8SAndreas Simbuerger BBPair StartExitBlocks = 29082d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 2909256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 291038fc0aedSTobias Grosser 29112d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 291217f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 2913acf80064SEli Friedman 291438fc0aedSTobias Grosser // TODO: Handle LICM 291538fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 291638fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 291738fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 2918cb1aef8dSTobias Grosser 2919cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 29202b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 292182f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 292282f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 2923cb1aef8dSTobias Grosser isl_ast_build_free(Build); 2924cb1aef8dSTobias Grosser 2925cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 2926cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2927cb1aef8dSTobias Grosser 292838fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 2929fa7b0802STobias Grosser 2930fa7b0802STobias Grosser NodeBuilder.initializeAfterRTH(); 293138fc0aedSTobias Grosser NodeBuilder.create(Root); 29328ed5e599STobias Grosser NodeBuilder.finalize(); 29335857b701STobias Grosser 2934bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 2935bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2936de244eb4STobias Grosser /// point in running it on a GPU. 2937bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 2938bc653f20STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 2939bc653f20STobias Grosser 29405857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 29415857b701STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 294238fc0aedSTobias Grosser } 294338fc0aedSTobias Grosser 2944e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 2945e938517eSTobias Grosser S = &CurrentScop; 294638fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 294738fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 294838fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 29497b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 295038fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2951e938517eSTobias Grosser 2952f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 2953f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 2954f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 2955bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 2956bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 2957f291c8d5SSiddharth Bhat if (containsInvalidKernelFunction(CurrentScop)) { 2958f291c8d5SSiddharth Bhat DEBUG( 2959f291c8d5SSiddharth Bhat dbgs() 2960f291c8d5SSiddharth Bhat << "Scop contains function which cannot be materialised in a GPU " 2961f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 2962bccaea57SSiddharth Bhat return false; 2963f291c8d5SSiddharth Bhat } 2964bccaea57SSiddharth Bhat 2965e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 2966e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 2967f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 296838fc0aedSTobias Grosser 296902ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 297032837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 297102ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 297202ca346eSSingapuram Sanjay Srivallabh } 297338fc0aedSTobias Grosser 2974b307ed4dSTobias Grosser freeOptions(PPCGScop); 2975f384594dSTobias Grosser freePPCGGen(PPCGGen); 2976e938517eSTobias Grosser gpu_prog_free(PPCGProg); 2977e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 2978e938517eSTobias Grosser 2979e938517eSTobias Grosser return true; 2980e938517eSTobias Grosser } 29819dfe4e7cSTobias Grosser 29829dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 29839dfe4e7cSTobias Grosser 29849dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 29859dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 29869dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 29879dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 29885cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 29899dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 29909dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 29919dfe4e7cSTobias Grosser 29929dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 29939dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 29949dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 29959dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 29969dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 29975cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 29989dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 29999dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 30009dfe4e7cSTobias Grosser 30019dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 30029dfe4e7cSTobias Grosser // region tree. 30039dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 30049dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 30059dfe4e7cSTobias Grosser } 30069dfe4e7cSTobias Grosser }; 300724222c73STobias Grosser } // namespace 30089dfe4e7cSTobias Grosser 30099dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 30109dfe4e7cSTobias Grosser 301117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 301217f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 301317f01968SSiddharth Bhat generator->Runtime = Runtime; 301417f01968SSiddharth Bhat generator->Architecture = Arch; 301517f01968SSiddharth Bhat return generator; 301617f01968SSiddharth Bhat } 30179dfe4e7cSTobias Grosser 30189dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 30199dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 30209dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 30219dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 30229dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 30239dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 30249dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 30255cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 30269dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 30279dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3028