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 115*a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 116*a82f2d26SSiddharth Bhat /// used by live range reordering. 117*a82f2d26SSiddharth Bhat /// 118*a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 119*a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 120*a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 121*a82f2d26SSiddharth Bhat struct MustKillsInfo { 122*a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 123*a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 124*a82f2d26SSiddharth Bhat /// 125*a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126*a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 127*a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 128*a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 129*a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 130*a82f2d26SSiddharth Bhat /// killed. 131*a82f2d26SSiddharth Bhat /// 132*a82f2d26SSiddharth Bhat /// We currently only derive kill information for phi nodes, as phi nodes 133*a82f2d26SSiddharth Bhat /// allow us to easily derive kill information. PHI nodes are not alive 134*a82f2d26SSiddharth Bhat /// outside the scop and can consequently all be "killed". [params] -> { 135*a82f2d26SSiddharth Bhat /// [Stmt_phantom[] -> ref_phantom[]] -> phi_ref[] } 136*a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 137*a82f2d26SSiddharth Bhat 138*a82f2d26SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr), TaggedMustKills(nullptr){}; 139*a82f2d26SSiddharth Bhat }; 140*a82f2d26SSiddharth Bhat 141*a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 142*a82f2d26SSiddharth Bhat /// 143*a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 144*a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 145*a82f2d26SSiddharth Bhat /// PPCG. 146*a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 147*a82f2d26SSiddharth Bhat const isl::space ParamSpace(isl::manage(S.getParamSpace())); 148*a82f2d26SSiddharth Bhat MustKillsInfo Info; 149*a82f2d26SSiddharth Bhat 150*a82f2d26SSiddharth Bhat // 1. Collect phi nodes in scop. 151*a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 152*a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 153*a82f2d26SSiddharth Bhat if (!SAI->isPHIKind()) 154*a82f2d26SSiddharth Bhat continue; 155*a82f2d26SSiddharth Bhat 156*a82f2d26SSiddharth Bhat KillMemIds.push_back(isl::manage(SAI->getBasePtrId())); 157*a82f2d26SSiddharth Bhat } 158*a82f2d26SSiddharth Bhat 159*a82f2d26SSiddharth Bhat Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 160*a82f2d26SSiddharth Bhat 161*a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 162*a82f2d26SSiddharth Bhat // schedule: 163*a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 164*a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 165*a82f2d26SSiddharth Bhat // at the cost of some code complexity. 166*a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 167*a82f2d26SSiddharth Bhat 168*a82f2d26SSiddharth Bhat for (isl::id &phiId : KillMemIds) { 169*a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 170*a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("SKill_phantom_").append(phiId.get_name()), 171*a82f2d26SSiddharth Bhat nullptr); 172*a82f2d26SSiddharth Bhat 173*a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 174*a82f2d26SSiddharth Bhat // 2. We need to construct a map: 175*a82f2d26SSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> phi_ref } 176*a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 177*a82f2d26SSiddharth Bhat // 2a. StmtToPhi: 178*a82f2d26SSiddharth Bhat // [param] -> { Stmt_phantom[] -> phi_ref[] } 179*a82f2d26SSiddharth Bhat // 2b. PhantomRefToPhi: 180*a82f2d26SSiddharth Bhat // [param] -> { ref_phantom[] -> phi_ref[] } 181*a82f2d26SSiddharth Bhat // 182*a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 183*a82f2d26SSiddharth Bhat // TaggedMustKill: 184*a82f2d26SSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 185*a82f2d26SSiddharth Bhat 186*a82f2d26SSiddharth Bhat // 2a. [param] -> { S_2[] -> phi_ref[] } 187*a82f2d26SSiddharth Bhat isl::map StmtToPhi = isl::map::universe(isl::space(ParamSpace)); 188*a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 189*a82f2d26SSiddharth Bhat StmtToPhi = StmtToPhi.set_tuple_id(isl::dim::out, isl::id(phiId)); 190*a82f2d26SSiddharth Bhat 191*a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 192*a82f2d26SSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + phiId.get_name(), nullptr); 193*a82f2d26SSiddharth Bhat 194*a82f2d26SSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> memref[] } 195*a82f2d26SSiddharth Bhat isl::map PhantomRefToPhi = isl::map::universe(isl::space(ParamSpace)); 196*a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::in, PhantomRefId); 197*a82f2d26SSiddharth Bhat PhantomRefToPhi = PhantomRefToPhi.set_tuple_id(isl::dim::out, phiId); 198*a82f2d26SSiddharth Bhat 199*a82f2d26SSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> memref[] } 200*a82f2d26SSiddharth Bhat isl::map TaggedMustKill = StmtToPhi.domain_product(PhantomRefToPhi); 201*a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 202*a82f2d26SSiddharth Bhat 203*a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 204*a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 205*a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 206*a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 207*a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 208*a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 209*a82f2d26SSiddharth Bhat 210*a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 211*a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 212*a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 213*a82f2d26SSiddharth Bhat else 214*a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 215*a82f2d26SSiddharth Bhat } 216*a82f2d26SSiddharth Bhat 217*a82f2d26SSiddharth Bhat return Info; 218*a82f2d26SSiddharth Bhat } 219*a82f2d26SSiddharth 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 30238fc0aedSTobias Grosser private: 30374dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 30474dc3cb4STobias Grosser /// 30574dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 30674dc3cb4STobias Grosser /// more. 30774dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 30874dc3cb4STobias Grosser 30913c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 31013c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3117287aeddSTobias Grosser 312fa7b0802STobias Grosser /// The current GPU context. 313fa7b0802STobias Grosser Value *GPUContext; 314fa7b0802STobias Grosser 315b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 316b513b491STobias Grosser std::vector<isl_id *> KernelIds; 317b513b491STobias Grosser 31832837fe3STobias Grosser /// A module containing GPU code. 31932837fe3STobias Grosser /// 32032837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 32132837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 32232837fe3STobias Grosser 32332837fe3STobias Grosser /// The GPU program we generate code for. 32432837fe3STobias Grosser gpu_prog *Prog; 32532837fe3STobias Grosser 32617f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 32717f01968SSiddharth Bhat GPURuntime Runtime; 32817f01968SSiddharth Bhat 32917f01968SSiddharth Bhat /// The GPU Architecture to target. 33017f01968SSiddharth Bhat GPUArch Arch; 33117f01968SSiddharth Bhat 332472f9654STobias Grosser /// Class to free isl_ids. 333472f9654STobias Grosser class IslIdDeleter { 334472f9654STobias Grosser public: 335472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 336472f9654STobias Grosser }; 337472f9654STobias Grosser 338472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 339472f9654STobias Grosser /// 340472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 341472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 342472f9654STobias Grosser 343edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 344edb885cbSTobias Grosser 34538fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 34638fc0aedSTobias Grosser /// 34738fc0aedSTobias Grosser /// These AST nodes can be of type: 34838fc0aedSTobias Grosser /// 34938fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 35038fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 35113c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 3525260c041STobias Grosser /// - In-kernel synchronization 3535260c041STobias Grosser /// - In-kernel memory copy statement 35438fc0aedSTobias Grosser /// 3551fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 3561fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 35732837fe3STobias Grosser 35813c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 35913c78e4dSTobias Grosser 36013c78e4dSTobias Grosser /// Create code for a data transfer statement 36113c78e4dSTobias Grosser /// 36213c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 36313c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 36413c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 36513c78e4dSTobias Grosser enum DataDirection Direction); 36613c78e4dSTobias Grosser 367edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 368edb885cbSTobias Grosser /// 369edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 370edb885cbSTobias Grosser /// 371f291c8d5SSiddharth Bhat /// @returns A pair, whose first element contains the set of values 372f291c8d5SSiddharth Bhat /// referenced by the kernel, and whose second element contains the 373f291c8d5SSiddharth Bhat /// set of functions referenced by the kernel. All functions in the 374f291c8d5SSiddharth Bhat /// second set satisfy isValidFunctionInKernel. 375f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 376f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 377edb885cbSTobias Grosser 37879a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 37979a947c2STobias Grosser /// 38079a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 38179a947c2STobias Grosser /// 38279a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 38379a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 38479a947c2STobias Grosser 385abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 386abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 387abed4969SSiddharth Bhat /// host pointers to the device. 388abed4969SSiddharth Bhat /// \note 389abed4969SSiddharth Bhat /// This is to be used only with managed memory 390abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 391abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 392abed4969SSiddharth Bhat 39379a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 39479a947c2STobias Grosser /// 39579a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 39679a947c2STobias Grosser /// 39779a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 39879a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 39979a947c2STobias Grosser 400a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 401a90be207SSiddharth Bhat /// parameters. 402a90be207SSiddharth Bhat /// 403a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 404a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 405a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 406a90be207SSiddharth Bhat /// parameter. 407a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 408a90be207SSiddharth Bhat int Index); 409a90be207SSiddharth Bhat 41079a947c2STobias Grosser /// Create kernel launch parameters. 41179a947c2STobias Grosser /// 41279a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 41379a947c2STobias Grosser /// @param F The kernel function that has been created. 41457693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 41579a947c2STobias Grosser /// 41679a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 41779a947c2STobias Grosser /// values that are passed to the kernel. 41857693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 41957693272STobias Grosser SetVector<Value *> SubtreeValues); 42079a947c2STobias Grosser 421b513b491STobias Grosser /// Create declarations for kernel variable. 422b513b491STobias Grosser /// 423b513b491STobias Grosser /// This includes shared memory declarations. 424b513b491STobias Grosser /// 425b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 426b513b491STobias Grosser /// @param FN The function into which to generate the variables. 427b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 428b513b491STobias Grosser 429c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 430c1c6a2a6STobias Grosser /// 431c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 432c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 433c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 434c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 435c1c6a2a6STobias Grosser /// as specified here. 436c1c6a2a6STobias Grosser /// 437c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 438c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 439c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 440c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 441c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 442c1c6a2a6STobias Grosser Value *BlockDimZ); 443c1c6a2a6STobias Grosser 44432837fe3STobias Grosser /// Create GPU kernel. 44532837fe3STobias Grosser /// 44632837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 44732837fe3STobias Grosser /// 44832837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 44932837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 45032837fe3STobias Grosser 45113c78e4dSTobias Grosser /// Generate code that computes the size of an array. 45213c78e4dSTobias Grosser /// 45313c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 45413c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 45513c78e4dSTobias Grosser 456aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 457aaabbbf8STobias Grosser /// 458aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 459aaabbbf8STobias Grosser /// 460aaabbbf8STobias Grosser /// Example: 461aaabbbf8STobias Grosser /// 462aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 463aaabbbf8STobias Grosser /// A[i + 42] += ... 464aaabbbf8STobias Grosser /// 465aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 466aaabbbf8STobias Grosser /// 467aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 468aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 469aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 470aaabbbf8STobias Grosser 47100bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 47200bb5a99STobias Grosser /// 47300bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 47400bb5a99STobias Grosser /// @param FN The function created for the kernel. 47500bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 47600bb5a99STobias Grosser 47732837fe3STobias Grosser /// Create kernel function. 47832837fe3STobias Grosser /// 47932837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 48032837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 48132837fe3STobias Grosser /// start block of this newly created function. 48232837fe3STobias Grosser /// 48332837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 484edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 485f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 486f291c8d5SSiddharth Bhat /// kernel. 487edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 488f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 489f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 49032837fe3STobias Grosser 49132837fe3STobias Grosser /// Create the declaration of a kernel function. 49232837fe3STobias Grosser /// 49332837fe3STobias Grosser /// The kernel function takes as arguments: 49432837fe3STobias Grosser /// 49532837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 496f6044bd0STobias Grosser /// - Host iterators 497c84a1995STobias Grosser /// - Parameters 49832837fe3STobias Grosser /// - Other LLVM Value references (TODO) 49932837fe3STobias Grosser /// 50032837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 501edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 502edb885cbSTobias Grosser /// 50332837fe3STobias Grosser /// @returns The newly declared function. 504edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 505edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 50632837fe3STobias Grosser 507472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 508472f9654STobias Grosser /// 509472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 510472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 511472f9654STobias Grosser 512f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 513f291c8d5SSiddharth Bhat /// 514f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 515f291c8d5SSiddharth Bhat /// SubtreeFunctions. 516f291c8d5SSiddharth Bhat /// 517f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 518f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 519f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 520f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 521f291c8d5SSiddharth Bhat /// 522f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 523f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 524f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 525f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 526f291c8d5SSiddharth Bhat /// 527f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 528f291c8d5SSiddharth Bhat /// this kernel. 529f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 530f291c8d5SSiddharth Bhat 531b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 532b513b491STobias Grosser /// 533b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 534b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 535b513b491STobias Grosser 536edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 537edb885cbSTobias Grosser /// 538edb885cbSTobias Grosser /// @param Expr The expression containing the call. 539edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 540edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 541edb885cbSTobias Grosser 5425260c041STobias Grosser /// Create an in-kernel synchronization call. 5435260c041STobias Grosser void createKernelSync(); 5445260c041STobias Grosser 54574dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 54674dc3cb4STobias Grosser /// 54774dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 54874dc3cb4STobias Grosser std::string createKernelASM(); 54974dc3cb4STobias Grosser 55074dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 55174dc3cb4STobias Grosser /// 55274dc3cb4STobias Grosser /// @param F The function to remove references to. 55374dc3cb4STobias Grosser void clearDominators(Function *F); 55474dc3cb4STobias Grosser 55574dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 55674dc3cb4STobias Grosser /// 55774dc3cb4STobias Grosser /// @param F The function to remove references to. 55874dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 55974dc3cb4STobias Grosser 56074dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 56174dc3cb4STobias Grosser /// 56274dc3cb4STobias Grosser /// @param F The function to remove references to. 56374dc3cb4STobias Grosser void clearLoops(Function *F); 56474dc3cb4STobias Grosser 56532837fe3STobias Grosser /// Finalize the generation of the kernel function. 56632837fe3STobias Grosser /// 56732837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 56832837fe3STobias Grosser /// dump its IR to stderr. 56957793596STobias Grosser /// 57057793596STobias Grosser /// @returns The Assembly string of the kernel. 57157793596STobias Grosser std::string finalizeKernelFunction(); 572fa7b0802STobias Grosser 57351dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 57451dfc275STobias Grosser /// 57551dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 576a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 57751dfc275STobias Grosser /// the kernel terminates. 57851dfc275STobias Grosser /// 57951dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 58051dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 58151dfc275STobias Grosser 5827287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 583fa7b0802STobias Grosser void allocateDeviceArrays(); 584fa7b0802STobias Grosser 5857287aeddSTobias Grosser /// Free all allocated device arrays. 5867287aeddSTobias Grosser void freeDeviceArrays(); 5877287aeddSTobias Grosser 588fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 589fa7b0802STobias Grosser /// 590fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 591fa7b0802STobias Grosser Value *createCallInitContext(); 592fa7b0802STobias Grosser 59379a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 59479a947c2STobias Grosser /// 59579a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 59679a947c2STobias Grosser /// 59779a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 59879a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 59979a947c2STobias Grosser 600fa7b0802STobias Grosser /// Create a call to free the GPU context. 601fa7b0802STobias Grosser /// 602fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 603fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 604fa7b0802STobias Grosser 6057287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6067287aeddSTobias Grosser /// 6077287aeddSTobias Grosser /// @param Size The size of memory to allocate 6087287aeddSTobias Grosser /// 6097287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 610fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6117287aeddSTobias Grosser 6127287aeddSTobias Grosser /// Create a call to free a device array. 6137287aeddSTobias Grosser /// 6147287aeddSTobias Grosser /// @param Array The device array to free. 6157287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 61613c78e4dSTobias Grosser 61713c78e4dSTobias Grosser /// Create a call to copy data from host to device. 61813c78e4dSTobias Grosser /// 61913c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 62013c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 62113c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 62213c78e4dSTobias Grosser Value *Size); 62313c78e4dSTobias Grosser 62413c78e4dSTobias Grosser /// Create a call to copy data from device to host. 62513c78e4dSTobias Grosser /// 62613c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 62713c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 62813c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 62913c78e4dSTobias Grosser Value *Size); 63057793596STobias Grosser 631abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 632abed4969SSiddharth Bhat /// \note 633abed4969SSiddharth Bhat /// This is to be used only with managed memory. 634abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 635abed4969SSiddharth Bhat 63657793596STobias Grosser /// Create a call to get a kernel from an assembly string. 63757793596STobias Grosser /// 63857793596STobias Grosser /// @param Buffer The string describing the kernel. 63957793596STobias Grosser /// @param Entry The name of the kernel function to call. 64057793596STobias Grosser /// 64157793596STobias Grosser /// @returns A pointer to a kernel object 64257793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 64357793596STobias Grosser 64457793596STobias Grosser /// Create a call to free a GPU kernel. 64557793596STobias Grosser /// 64657793596STobias Grosser /// @param GPUKernel THe kernel to free. 64757793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 64879a947c2STobias Grosser 64979a947c2STobias Grosser /// Create a call to launch a GPU kernel. 65079a947c2STobias Grosser /// 65179a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 65279a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 65379a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 65479a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 65579a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 65679a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 657a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 65879a947c2STobias Grosser /// the parameter values passed for each kernel argument. 65979a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 66079a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 66179a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 66279a947c2STobias Grosser Value *Parameters); 6631fb9b64dSTobias Grosser }; 6641fb9b64dSTobias Grosser 665fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 666750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 667750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 668750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 669750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 670750160e2STobias Grosser 671fa7b0802STobias Grosser GPUContext = createCallInitContext(); 672abed4969SSiddharth Bhat 673abed4969SSiddharth Bhat if (!ManagedMemory) 674fa7b0802STobias Grosser allocateDeviceArrays(); 675fa7b0802STobias Grosser } 676fa7b0802STobias Grosser 677fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 678abed4969SSiddharth Bhat if (!ManagedMemory) 6797287aeddSTobias Grosser freeDeviceArrays(); 680abed4969SSiddharth Bhat 681fa7b0802STobias Grosser createCallFreeContext(GPUContext); 682fa7b0802STobias Grosser IslNodeBuilder::finalize(); 683fa7b0802STobias Grosser } 684fa7b0802STobias Grosser 685fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 686abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 687abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 688fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 689fa7b0802STobias Grosser 690fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 691fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 69213c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 6937287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 6947287aeddSTobias Grosser DevArrayName.append(Array->name); 695fa7b0802STobias Grosser 69613c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 697aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 698aaabbbf8STobias Grosser if (Offset) 699aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 700aaabbbf8STobias Grosser ArraySize, 701aaabbbf8STobias Grosser Builder.CreateMul(Offset, 702aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 7037287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7047287aeddSTobias Grosser DevArray->setName(DevArrayName); 70513c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 706fa7b0802STobias Grosser } 707fa7b0802STobias Grosser 708fa7b0802STobias Grosser isl_ast_build_free(Build); 709fa7b0802STobias Grosser } 710fa7b0802STobias Grosser 711c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 712c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 713c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 714c1c6a2a6STobias Grosser 715c1c6a2a6STobias Grosser for (auto &F : *M) { 716c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 717c1c6a2a6STobias Grosser continue; 718c1c6a2a6STobias Grosser 719c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 720c1c6a2a6STobias Grosser 721c1c6a2a6STobias Grosser Metadata *Elements[] = { 722c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 723c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 724c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 725c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 726c1c6a2a6STobias Grosser }; 727c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 728c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 729c1c6a2a6STobias Grosser } 730c1c6a2a6STobias Grosser } 731c1c6a2a6STobias Grosser 7327287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 733abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 73413c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 73513c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 7367287aeddSTobias Grosser } 7377287aeddSTobias Grosser 73857793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 73957793596STobias Grosser const char *Name = "polly_getKernel"; 74057793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 74157793596STobias Grosser Function *F = M->getFunction(Name); 74257793596STobias Grosser 74357793596STobias Grosser // If F is not available, declare it. 74457793596STobias Grosser if (!F) { 74557793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 74657793596STobias Grosser std::vector<Type *> Args; 74757793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 74857793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 74957793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 75057793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 75157793596STobias Grosser } 75257793596STobias Grosser 75357793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 75457793596STobias Grosser } 75557793596STobias Grosser 75679a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 75779a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 75879a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 75979a947c2STobias Grosser Function *F = M->getFunction(Name); 76079a947c2STobias Grosser 76179a947c2STobias Grosser // If F is not available, declare it. 76279a947c2STobias Grosser if (!F) { 76379a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 76479a947c2STobias Grosser std::vector<Type *> Args; 76579a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 76679a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 76779a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 76879a947c2STobias Grosser } 76979a947c2STobias Grosser 77079a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 77179a947c2STobias Grosser } 77279a947c2STobias Grosser 77379a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 77479a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 77579a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 77679a947c2STobias Grosser Value *Parameters) { 77779a947c2STobias Grosser const char *Name = "polly_launchKernel"; 77879a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 77979a947c2STobias Grosser Function *F = M->getFunction(Name); 78079a947c2STobias Grosser 78179a947c2STobias Grosser // If F is not available, declare it. 78279a947c2STobias Grosser if (!F) { 78379a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 78479a947c2STobias Grosser std::vector<Type *> Args; 78579a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 78679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 78779a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 78879a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 78979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79079a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 79179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79279a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 79379a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 79479a947c2STobias Grosser } 79579a947c2STobias Grosser 796ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 79779a947c2STobias Grosser BlockDimZ, Parameters}); 79879a947c2STobias Grosser } 79979a947c2STobias Grosser 80057793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 80157793596STobias Grosser const char *Name = "polly_freeKernel"; 80257793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 80357793596STobias Grosser Function *F = M->getFunction(Name); 80457793596STobias Grosser 80557793596STobias Grosser // If F is not available, declare it. 80657793596STobias Grosser if (!F) { 80757793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 80857793596STobias Grosser std::vector<Type *> Args; 80957793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 81057793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 81157793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 81257793596STobias Grosser } 81357793596STobias Grosser 81457793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 81557793596STobias Grosser } 81657793596STobias Grosser 8177287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 818abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 819abed4969SSiddharth Bhat "for device"); 8207287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 8217287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8227287aeddSTobias Grosser Function *F = M->getFunction(Name); 8237287aeddSTobias Grosser 8247287aeddSTobias Grosser // If F is not available, declare it. 8257287aeddSTobias Grosser if (!F) { 8267287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 8277287aeddSTobias Grosser std::vector<Type *> Args; 8287287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 8297287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 8307287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 8317287aeddSTobias Grosser } 8327287aeddSTobias Grosser 8337287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 8347287aeddSTobias Grosser } 8357287aeddSTobias Grosser 836fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 837abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 838abed4969SSiddharth Bhat "for device"); 839fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 840fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 841fa7b0802STobias Grosser Function *F = M->getFunction(Name); 842fa7b0802STobias Grosser 843fa7b0802STobias Grosser // If F is not available, declare it. 844fa7b0802STobias Grosser if (!F) { 845fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 846fa7b0802STobias Grosser std::vector<Type *> Args; 847fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 848fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 849fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 850fa7b0802STobias Grosser } 851fa7b0802STobias Grosser 852fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 853fa7b0802STobias Grosser } 854fa7b0802STobias Grosser 85513c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 85613c78e4dSTobias Grosser Value *DeviceData, 85713c78e4dSTobias Grosser Value *Size) { 858abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 859abed4969SSiddharth Bhat "device and host"); 86013c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 86113c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 86213c78e4dSTobias Grosser Function *F = M->getFunction(Name); 86313c78e4dSTobias Grosser 86413c78e4dSTobias Grosser // If F is not available, declare it. 86513c78e4dSTobias Grosser if (!F) { 86613c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 86713c78e4dSTobias Grosser std::vector<Type *> Args; 86813c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 86913c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87013c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 87113c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 87213c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 87313c78e4dSTobias Grosser } 87413c78e4dSTobias Grosser 87513c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 87613c78e4dSTobias Grosser } 87713c78e4dSTobias Grosser 87813c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 87913c78e4dSTobias Grosser Value *HostData, 88013c78e4dSTobias Grosser Value *Size) { 881abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 882abed4969SSiddharth Bhat "device and host"); 88313c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 88413c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 88513c78e4dSTobias Grosser Function *F = M->getFunction(Name); 88613c78e4dSTobias Grosser 88713c78e4dSTobias Grosser // If F is not available, declare it. 88813c78e4dSTobias Grosser if (!F) { 88913c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 89013c78e4dSTobias Grosser std::vector<Type *> Args; 89113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89213c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89313c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 89413c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 89513c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 89613c78e4dSTobias Grosser } 89713c78e4dSTobias Grosser 89813c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 89913c78e4dSTobias Grosser } 90013c78e4dSTobias Grosser 901abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 902abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 903abed4969SSiddharth Bhat "managed memory"); 904abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 905abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 906abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 907abed4969SSiddharth Bhat 908abed4969SSiddharth Bhat // If F is not available, declare it. 909abed4969SSiddharth Bhat if (!F) { 910abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 911abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 912abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 913abed4969SSiddharth Bhat } 914abed4969SSiddharth Bhat 915abed4969SSiddharth Bhat Builder.CreateCall(F); 916abed4969SSiddharth Bhat } 917abed4969SSiddharth Bhat 918fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 91917f01968SSiddharth Bhat const char *Name; 92017f01968SSiddharth Bhat 92117f01968SSiddharth Bhat switch (Runtime) { 92217f01968SSiddharth Bhat case GPURuntime::CUDA: 92317f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 92417f01968SSiddharth Bhat break; 92517f01968SSiddharth Bhat case GPURuntime::OpenCL: 92617f01968SSiddharth Bhat Name = "polly_initContextCL"; 92717f01968SSiddharth Bhat break; 92817f01968SSiddharth Bhat } 92917f01968SSiddharth Bhat 930fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 931fa7b0802STobias Grosser Function *F = M->getFunction(Name); 932fa7b0802STobias Grosser 933fa7b0802STobias Grosser // If F is not available, declare it. 934fa7b0802STobias Grosser if (!F) { 935fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 936fa7b0802STobias Grosser std::vector<Type *> Args; 937fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 938fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 939fa7b0802STobias Grosser } 940fa7b0802STobias Grosser 941fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 942fa7b0802STobias Grosser } 943fa7b0802STobias Grosser 944fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 945fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 946fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 947fa7b0802STobias Grosser Function *F = M->getFunction(Name); 948fa7b0802STobias Grosser 949fa7b0802STobias Grosser // If F is not available, declare it. 950fa7b0802STobias Grosser if (!F) { 951fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 952fa7b0802STobias Grosser std::vector<Type *> Args; 953fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 954fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 955fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 956fa7b0802STobias Grosser } 957fa7b0802STobias Grosser 958fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 959fa7b0802STobias Grosser } 960fa7b0802STobias Grosser 9615260c041STobias Grosser /// Check if one string is a prefix of another. 9625260c041STobias Grosser /// 9635260c041STobias Grosser /// @param String The string in which to look for the prefix. 9645260c041STobias Grosser /// @param Prefix The prefix to look for. 9655260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 9665260c041STobias Grosser return String.find(Prefix) == 0; 9675260c041STobias Grosser } 9685260c041STobias Grosser 96913c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 97013c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 97113c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 97213c78e4dSTobias Grosser 97313c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 97413c78e4dSTobias Grosser auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 97513c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 97613c78e4dSTobias Grosser 97713c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 97813c78e4dSTobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 97913c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 98013c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 98113c78e4dSTobias Grosser } 98213c78e4dSTobias Grosser 98313c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 984b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 985b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 98613c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 98713c78e4dSTobias Grosser } 98813c78e4dSTobias Grosser isl_ast_build_free(Build); 98913c78e4dSTobias Grosser return ArraySize; 99013c78e4dSTobias Grosser } 99113c78e4dSTobias Grosser 992aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 993aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 994aaabbbf8STobias Grosser return nullptr; 995aaabbbf8STobias Grosser 996aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 997aaabbbf8STobias Grosser 998aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 999aaabbbf8STobias Grosser 1000aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1001aaabbbf8STobias Grosser 1002aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1003aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1004aaabbbf8STobias Grosser 1005aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 1006aaabbbf8STobias Grosser isl_set_free(Min); 1007aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1008aaabbbf8STobias Grosser isl_ast_build_free(Build); 1009aaabbbf8STobias Grosser return nullptr; 1010aaabbbf8STobias Grosser } 1011aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1012aaabbbf8STobias Grosser 1013aaabbbf8STobias Grosser isl_ast_expr *Result = 1014aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1015aaabbbf8STobias Grosser 1016aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1017aaabbbf8STobias Grosser if (i > 0) { 1018aaabbbf8STobias Grosser isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 1019aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1020aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 1021aaabbbf8STobias Grosser } 1022aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1023aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1024aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 1025aaabbbf8STobias Grosser } 1026aaabbbf8STobias Grosser 1027aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 1028aaabbbf8STobias Grosser isl_set_free(Min); 1029aaabbbf8STobias Grosser isl_ast_build_free(Build); 1030aaabbbf8STobias Grosser 1031aaabbbf8STobias Grosser return ResultValue; 1032aaabbbf8STobias Grosser } 1033aaabbbf8STobias Grosser 1034abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1035abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1036abed4969SSiddharth Bhat 1037abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 1038abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1039abed4969SSiddharth Bhat "with managed memory"); 1040abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1041abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1042abed4969SSiddharth Bhat return it->second; 1043abed4969SSiddharth Bhat } else { 1044abed4969SSiddharth Bhat Value *HostPtr; 1045abed4969SSiddharth Bhat 1046abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 1047abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1048abed4969SSiddharth Bhat else 1049abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 1050abed4969SSiddharth Bhat 1051abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 1052abed4969SSiddharth Bhat if (Offset) { 1053abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 1054abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1055abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 1056abed4969SSiddharth Bhat } 1057abed4969SSiddharth Bhat 1058abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1059abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 1060abed4969SSiddharth Bhat return HostPtr; 1061abed4969SSiddharth Bhat } 1062abed4969SSiddharth Bhat } 1063abed4969SSiddharth Bhat 106413c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 106513c78e4dSTobias Grosser enum DataDirection Direction) { 1066abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 106713c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 106813c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 106913c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 107013c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 107113c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 107213c78e4dSTobias Grosser 107313c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1074aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 107513c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 107613c78e4dSTobias Grosser 1077b06ff457STobias Grosser Value *HostPtr; 1078b06ff457STobias Grosser 1079b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1080b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1081b06ff457STobias Grosser else 1082b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 108313c78e4dSTobias Grosser 1084aaabbbf8STobias Grosser if (Offset) { 1085aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1086aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1087aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1088aaabbbf8STobias Grosser } 1089aaabbbf8STobias Grosser 109013c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 109113c78e4dSTobias Grosser 1092aaabbbf8STobias Grosser if (Offset) { 1093aaabbbf8STobias Grosser Size = Builder.CreateSub( 1094ff40087aSTobias Grosser Size, Builder.CreateMul( 1095ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1096aaabbbf8STobias Grosser } 1097aaabbbf8STobias Grosser 109813c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 109913c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 110013c78e4dSTobias Grosser else 110113c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 110213c78e4dSTobias Grosser 110313c78e4dSTobias Grosser isl_id_free(Id); 110413c78e4dSTobias Grosser isl_ast_expr_free(Arg); 110513c78e4dSTobias Grosser isl_ast_expr_free(Expr); 110613c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 110713c78e4dSTobias Grosser } 110813c78e4dSTobias Grosser 11091fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 111032837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 111132837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 111232837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 111332837fe3STobias Grosser isl_id_free(Id); 111432837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 111532837fe3STobias Grosser 111632837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 111732837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 111832837fe3STobias Grosser createKernel(UserStmt); 111932837fe3STobias Grosser isl_ast_expr_free(Expr); 112032837fe3STobias Grosser return; 112132837fe3STobias Grosser } 112232837fe3STobias Grosser 112313c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1124abed4969SSiddharth Bhat if (!ManagedMemory) 112513c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1126abed4969SSiddharth Bhat else 1127abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1128abed4969SSiddharth Bhat 112932837fe3STobias Grosser isl_ast_expr_free(Expr); 113013c78e4dSTobias Grosser return; 113113c78e4dSTobias Grosser } 113213c78e4dSTobias Grosser 113313c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1134abed4969SSiddharth Bhat if (!ManagedMemory) { 113513c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1136abed4969SSiddharth Bhat } else { 1137abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1138abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1139abed4969SSiddharth Bhat } 114013c78e4dSTobias Grosser isl_ast_expr_free(Expr); 114138fc0aedSTobias Grosser return; 114238fc0aedSTobias Grosser } 114338fc0aedSTobias Grosser 11445260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 11455260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 11465260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 11475260c041STobias Grosser isl_id_free(Anno); 11485260c041STobias Grosser 11495260c041STobias Grosser switch (KernelStmt->type) { 11505260c041STobias Grosser case ppcg_kernel_domain: 1151edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 11525260c041STobias Grosser isl_ast_node_free(UserStmt); 11535260c041STobias Grosser return; 11545260c041STobias Grosser case ppcg_kernel_copy: 1155b513b491STobias Grosser createKernelCopy(KernelStmt); 11565260c041STobias Grosser isl_ast_expr_free(Expr); 11575260c041STobias Grosser isl_ast_node_free(UserStmt); 11585260c041STobias Grosser return; 11595260c041STobias Grosser case ppcg_kernel_sync: 11605260c041STobias Grosser createKernelSync(); 11615260c041STobias Grosser isl_ast_expr_free(Expr); 11625260c041STobias Grosser isl_ast_node_free(UserStmt); 11635260c041STobias Grosser return; 11645260c041STobias Grosser } 11655260c041STobias Grosser 11665260c041STobias Grosser isl_ast_expr_free(Expr); 11675260c041STobias Grosser isl_ast_node_free(UserStmt); 11685260c041STobias Grosser return; 11695260c041STobias Grosser } 1170b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1171b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1172b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1173b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1174b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1175b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1176b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1177b513b491STobias Grosser 1178b513b491STobias Grosser if (KernelStmt->u.c.read) { 1179b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1180b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1181b513b491STobias Grosser } else { 1182b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1183b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1184b513b491STobias Grosser } 1185b513b491STobias Grosser } 11865260c041STobias Grosser 1187edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1188edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1189edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1190edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1191edb885cbSTobias Grosser 1192edb885cbSTobias Grosser LoopToScevMapT LTS; 1193edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1194edb885cbSTobias Grosser 1195edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1196edb885cbSTobias Grosser 1197edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1198edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1199edb885cbSTobias Grosser else 1200a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1201edb885cbSTobias Grosser } 1202edb885cbSTobias Grosser 12035260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 12045260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 120517f01968SSiddharth Bhat 120617f01968SSiddharth Bhat Function *Sync; 120717f01968SSiddharth Bhat 120817f01968SSiddharth Bhat switch (Arch) { 120917f01968SSiddharth Bhat case GPUArch::NVPTX64: 121017f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 121117f01968SSiddharth Bhat break; 121217f01968SSiddharth Bhat } 121317f01968SSiddharth Bhat 12145260c041STobias Grosser Builder.CreateCall(Sync, {}); 12155260c041STobias Grosser } 12165260c041STobias Grosser 1217edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1218edb885cbSTobias Grosser /// 1219edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1220edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1221edb885cbSTobias Grosser /// 1222edb885cbSTobias Grosser /// @param Node The node to collect references for. 1223edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1224edb885cbSTobias Grosser /// 1225edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1226edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1227edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1228edb885cbSTobias Grosser return isl_bool_true; 1229edb885cbSTobias Grosser 1230edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1231edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1232edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1233edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1234edb885cbSTobias Grosser isl_id_free(Id); 1235edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1236edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1237edb885cbSTobias Grosser 1238edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1239edb885cbSTobias Grosser return isl_bool_true; 1240edb885cbSTobias Grosser 1241edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1242edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1243edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1244edb885cbSTobias Grosser isl_id_free(Id); 1245edb885cbSTobias Grosser 124600bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1247edb885cbSTobias Grosser 1248edb885cbSTobias Grosser return isl_bool_true; 1249edb885cbSTobias Grosser } 1250edb885cbSTobias Grosser 1251f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 1252f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) { 1253f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1254f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 1255f291c8d5SSiddharth Bhat // all variants of the intrinsic "llvm.sqrt.*" 1256f291c8d5SSiddharth Bhat return F->isIntrinsic() && F->getName().startswith("llvm.sqrt"); 1257f291c8d5SSiddharth Bhat } 1258f291c8d5SSiddharth Bhat 1259f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1260f291c8d5SSiddharth Bhat /// 1261f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1262f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1263f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1264f291c8d5SSiddharth Bhat /// `Function`s. 1265f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1266f291c8d5SSiddharth Bhat 1267f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1268f291c8d5SSiddharth Bhat static SetVector<Function *> 1269f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1270f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1271f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1272f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1273f291c8d5SSiddharth Bhat if (F) { 1274f291c8d5SSiddharth Bhat assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1275f291c8d5SSiddharth Bhat "this point if an invalid function " 1276f291c8d5SSiddharth Bhat "were present in a kernel."); 1277f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1278f291c8d5SSiddharth Bhat } 1279f291c8d5SSiddharth Bhat } 1280f291c8d5SSiddharth Bhat return SubtreeFunctions; 1281f291c8d5SSiddharth Bhat } 1282f291c8d5SSiddharth Bhat 1283f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 1284f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1285edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1286edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1287edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1288edb885cbSTobias Grosser SubtreeReferences References = { 1289edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1290edb885cbSTobias Grosser 1291edb885cbSTobias Grosser for (const auto &I : IDToValue) 1292edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1293edb885cbSTobias Grosser 1294edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1295edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1296edb885cbSTobias Grosser 1297edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1298edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1299edb885cbSTobias Grosser 1300edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1301d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1302edb885cbSTobias Grosser 1303edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1304edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1305edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1306edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1307edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1308edb885cbSTobias Grosser SubtreeValues.remove(Val); 1309edb885cbSTobias Grosser isl_id_free(Id); 1310edb885cbSTobias Grosser } 1311edb885cbSTobias Grosser isl_space_free(Space); 1312edb885cbSTobias Grosser 1313edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1314edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1315edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1316edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1317edb885cbSTobias Grosser SubtreeValues.remove(Val); 1318edb885cbSTobias Grosser isl_id_free(Id); 1319edb885cbSTobias Grosser } 1320edb885cbSTobias Grosser 1321f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1322f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1323f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1324f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1325f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1326f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1327f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1328f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1329f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 1330f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 1331f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SubtreeValues)); 1332f291c8d5SSiddharth Bhat 1333f291c8d5SSiddharth Bhat return std::make_pair(ValidSubtreeValues, ValidSubtreeFunctions); 1334edb885cbSTobias Grosser } 1335edb885cbSTobias Grosser 133674dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 133774dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 133874dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 133974dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 134074dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 134174dc3cb4STobias Grosser 134274dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 134374dc3cb4STobias Grosser DT.eraseNode(BB); 134474dc3cb4STobias Grosser } 134574dc3cb4STobias Grosser 134674dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 134774dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 134874dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 134974dc3cb4STobias Grosser if (L) 135074dc3cb4STobias Grosser SE.forgetLoop(L); 135174dc3cb4STobias Grosser } 135274dc3cb4STobias Grosser } 135374dc3cb4STobias Grosser 135474dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(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 LI.removeBlock(&BB); 136074dc3cb4STobias Grosser } 136174dc3cb4STobias Grosser } 136274dc3cb4STobias Grosser 136379a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 136479a947c2STobias Grosser std::vector<Value *> Sizes; 136579a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 136679a947c2STobias Grosser 136779a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 136879a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 136979a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 137079a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 137179a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 137279a947c2STobias Grosser Sizes.push_back(Res); 137379a947c2STobias Grosser } 137479a947c2STobias Grosser isl_ast_build_free(Context); 137579a947c2STobias Grosser 137679a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 137779a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 137879a947c2STobias Grosser 137979a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 138079a947c2STobias Grosser } 138179a947c2STobias Grosser 138279a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 138379a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 138479a947c2STobias Grosser std::vector<Value *> Sizes; 138579a947c2STobias Grosser 138679a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 138779a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 138879a947c2STobias Grosser Sizes.push_back(Res); 138979a947c2STobias Grosser } 139079a947c2STobias Grosser 139179a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 139279a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 139379a947c2STobias Grosser 139479a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 139579a947c2STobias Grosser } 139679a947c2STobias Grosser 1397a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1398a90be207SSiddharth Bhat Instruction *Param, int Index) { 1399a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1400a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1401a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1402a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1403a90be207SSiddharth Bhat } 1404a90be207SSiddharth Bhat 140557693272STobias Grosser Value * 140657693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 140757693272STobias Grosser SetVector<Value *> SubtreeValues) { 1408a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1409a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1410a90be207SSiddharth Bhat 1411a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 141279a947c2STobias Grosser 141379a947c2STobias Grosser BasicBlock *EntryBlock = 141479a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 141567726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 141679a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 141767726b32STobias Grosser Instruction *Parameters = new AllocaInst( 141867726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 141979a947c2STobias Grosser 142079a947c2STobias Grosser int Index = 0; 142179a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 142279a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 142379a947c2STobias Grosser continue; 142479a947c2STobias Grosser 142579a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 142679a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 142779a947c2STobias Grosser 1428a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1429a90be207SSiddharth Bhat 1430abed4969SSiddharth Bhat Value *DevArray = nullptr; 1431abed4969SSiddharth Bhat if (ManagedMemory) { 1432abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1433abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1434abed4969SSiddharth Bhat } else { 1435abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 143679a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1437abed4969SSiddharth Bhat } 1438abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1439abed4969SSiddharth Bhat "initialized"); 1440aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1441aaabbbf8STobias Grosser 1442aaabbbf8STobias Grosser if (Offset) { 1443aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1444aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1445aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1446aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1447aaabbbf8STobias Grosser } 1448fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1449fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1450aaabbbf8STobias Grosser 1451fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1452abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1453abed4969SSiddharth Bhat if (ManagedMemory) 1454abed4969SSiddharth Bhat ValPtr = DevArray; 1455abed4969SSiddharth Bhat else 1456abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1457abed4969SSiddharth Bhat 1458abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1459abed4969SSiddharth Bhat " to be stored into Parameters"); 1460fe74a7a1STobias Grosser Value *ValPtrCast = 1461fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1462fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1463fe74a7a1STobias Grosser } else { 146467726b32STobias Grosser Instruction *Param = 146567726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 146667726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 146779a947c2STobias Grosser EntryBlock->getTerminator()); 146879a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 146979a947c2STobias Grosser Value *ParamTyped = 147079a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 147179a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1472fe74a7a1STobias Grosser } 147379a947c2STobias Grosser Index++; 147479a947c2STobias Grosser } 147579a947c2STobias Grosser 1476a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1477a490147cSTobias Grosser 1478a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1479a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1480a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1481a490147cSTobias Grosser isl_id_free(Id); 1482a90be207SSiddharth Bhat 1483a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1484a90be207SSiddharth Bhat 148567726b32STobias Grosser Instruction *Param = 148667726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 148767726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1488a490147cSTobias Grosser EntryBlock->getTerminator()); 1489a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1490a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1491a490147cSTobias Grosser Index++; 1492a490147cSTobias Grosser } 1493a490147cSTobias Grosser 1494d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1495d8b94bcaSTobias Grosser 1496d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1497d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1498d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1499d8b94bcaSTobias Grosser isl_id_free(Id); 1500a90be207SSiddharth Bhat 1501a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1502a90be207SSiddharth Bhat 150367726b32STobias Grosser Instruction *Param = 150467726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 150567726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1506d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1507d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1508a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1509d8b94bcaSTobias Grosser Index++; 1510d8b94bcaSTobias Grosser } 1511d8b94bcaSTobias Grosser 151257693272STobias Grosser for (auto Val : SubtreeValues) { 1513a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1514a90be207SSiddharth Bhat 151567726b32STobias Grosser Instruction *Param = 151667726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 151767726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 151857693272STobias Grosser EntryBlock->getTerminator()); 151957693272STobias Grosser Builder.CreateStore(Val, Param); 1520a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1521a90be207SSiddharth Bhat Index++; 1522a90be207SSiddharth Bhat } 1523a90be207SSiddharth Bhat 1524a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1525a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1526a90be207SSiddharth Bhat Instruction *Param = 1527a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1528a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1529a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1530a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1531a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 153257693272STobias Grosser Index++; 153357693272STobias Grosser } 153457693272STobias Grosser 153579a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 153679a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 153779a947c2STobias Grosser Launch + "_params_i8ptr", Location); 153879a947c2STobias Grosser } 153979a947c2STobias Grosser 1540f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1541f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1542f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1543f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1544f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1545f291c8d5SSiddharth Bhat if (!Clone) 1546f291c8d5SSiddharth Bhat Clone = 1547f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1548f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1549f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1550f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1551f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1552f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1553f291c8d5SSiddharth Bhat } 1554f291c8d5SSiddharth Bhat } 155532837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 155632837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 155732837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 155832837fe3STobias Grosser isl_id_free(Id); 155932837fe3STobias Grosser isl_ast_node_free(KernelStmt); 156032837fe3STobias Grosser 1561bc653f20STobias Grosser if (Kernel->n_grid > 1) 1562bc653f20STobias Grosser DeepestParallel = 1563bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1564bc653f20STobias Grosser else 1565bc653f20STobias Grosser DeepestSequential = 1566bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1567bc653f20STobias Grosser 1568c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1569c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1570c1c6a2a6STobias Grosser 1571f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1572f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1573f291c8d5SSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1574edb885cbSTobias Grosser 157532837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 157632837fe3STobias Grosser 157732837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1578472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1579edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1580587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1581b06ff457STobias Grosser ScalarMap.clear(); 158232837fe3STobias Grosser 1583edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1584edb885cbSTobias Grosser 1585edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1586edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1587edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1588edb885cbSTobias Grosser for (const Loop *L : Loops) { 1589edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1590edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1591edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1592edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1593edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1594edb885cbSTobias Grosser SubtreeValues.insert(V); 1595edb885cbSTobias Grosser } 1596edb885cbSTobias Grosser 1597f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1598f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 159932837fe3STobias Grosser 160059ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 160159ab0705STobias Grosser 160251dfc275STobias Grosser finalizeKernelArguments(Kernel); 160374dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 1604c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 160574dc3cb4STobias Grosser clearDominators(F); 160674dc3cb4STobias Grosser clearScalarEvolution(F); 160774dc3cb4STobias Grosser clearLoops(F); 160874dc3cb4STobias Grosser 1609472f9654STobias Grosser IDToValue = HostIDs; 161032837fe3STobias Grosser 1611b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1612b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1613edb885cbSTobias Grosser EscapeMap.clear(); 1614edb885cbSTobias Grosser IDToSAI.clear(); 161574dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 161674dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 16174d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 161874dc3cb4STobias Grosser LocalArrays.clear(); 1619edb885cbSTobias Grosser 162051dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 162151dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 162257693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 162379a947c2STobias Grosser 162457793596STobias Grosser std::string Name = "kernel_" + std::to_string(Kernel->id); 162557793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 162657793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 162757793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 162879a947c2STobias Grosser 162979a947c2STobias Grosser Value *GridDimX, *GridDimY; 163079a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 163179a947c2STobias Grosser 163279a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 163379a947c2STobias Grosser BlockDimZ, Parameters); 163457793596STobias Grosser createCallFreeKernel(GPUKernel); 1635b513b491STobias Grosser 1636b513b491STobias Grosser for (auto Id : KernelIds) 1637b513b491STobias Grosser isl_id_free(Id); 1638b513b491STobias Grosser 1639b513b491STobias Grosser KernelIds.clear(); 164032837fe3STobias Grosser } 164132837fe3STobias Grosser 164232837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 164332837fe3STobias Grosser /// 164432837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 164532837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1646d277fedaSSiddharth Bhat std::string Ret = ""; 164732837fe3STobias Grosser 1648d277fedaSSiddharth Bhat if (!is64Bit) { 1649d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1650d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1651d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1652d277fedaSSiddharth Bhat } else { 1653d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1654d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1655d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1656d277fedaSSiddharth Bhat } 165732837fe3STobias Grosser 165832837fe3STobias Grosser return Ret; 165932837fe3STobias Grosser } 166032837fe3STobias Grosser 1661edb885cbSTobias Grosser Function * 1662edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1663edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 166432837fe3STobias Grosser std::vector<Type *> Args; 166532837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 166632837fe3STobias Grosser 166732837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 166832837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 166932837fe3STobias Grosser continue; 167032837fe3STobias Grosser 1671fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1672fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1673fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1674fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 1675fe74a7a1STobias Grosser } else { 1676d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1677d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 167832837fe3STobias Grosser } 1679fe74a7a1STobias Grosser } 168032837fe3STobias Grosser 1681f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1682f6044bd0STobias Grosser 1683f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) 1684f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 1685f6044bd0STobias Grosser 1686c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1687c84a1995STobias Grosser 1688cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1689cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1690cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1691cf66ef26STobias Grosser isl_id_free(Id); 1692cf66ef26STobias Grosser Args.push_back(Val->getType()); 1693cf66ef26STobias Grosser } 1694c84a1995STobias Grosser 1695edb885cbSTobias Grosser for (auto *V : SubtreeValues) 1696edb885cbSTobias Grosser Args.push_back(V->getType()); 1697edb885cbSTobias Grosser 169832837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 169932837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 170032837fe3STobias Grosser GPUModule.get()); 170117f01968SSiddharth Bhat 170217f01968SSiddharth Bhat switch (Arch) { 170317f01968SSiddharth Bhat case GPUArch::NVPTX64: 170432837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 170517f01968SSiddharth Bhat break; 170617f01968SSiddharth Bhat } 170732837fe3STobias Grosser 170832837fe3STobias Grosser auto Arg = FN->arg_begin(); 170932837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 171032837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 171132837fe3STobias Grosser continue; 171232837fe3STobias Grosser 1713edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1714edb885cbSTobias Grosser 1715edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1716edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1717edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1718edb885cbSTobias Grosser Value *Val = &*Arg; 1719edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1720edb885cbSTobias Grosser isl_ast_build *Build = 1721edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1722f5aff704SRoman Gareev Sizes.push_back(nullptr); 1723edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1724edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1725edb885cbSTobias Grosser Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1726edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1727edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1728edb885cbSTobias Grosser } 1729edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 17304d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 173174dc3cb4STobias Grosser LocalArrays.push_back(Val); 1732edb885cbSTobias Grosser 1733edb885cbSTobias Grosser isl_ast_build_free(Build); 1734b513b491STobias Grosser KernelIds.push_back(Id); 1735edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 173632837fe3STobias Grosser Arg++; 173732837fe3STobias Grosser } 173832837fe3STobias Grosser 1739f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1740f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1741f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1742f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1743f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1744f6044bd0STobias Grosser Arg++; 1745f6044bd0STobias Grosser } 1746f6044bd0STobias Grosser 1747c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1748c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1749c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 175012453403STobias Grosser Value *Val = IDToValue[Id]; 175112453403STobias Grosser ValueMap[Val] = &*Arg; 1752c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1753c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1754c84a1995STobias Grosser Arg++; 1755c84a1995STobias Grosser } 1756c84a1995STobias Grosser 1757edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1758edb885cbSTobias Grosser Arg->setName(V->getName()); 1759edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1760edb885cbSTobias Grosser Arg++; 1761edb885cbSTobias Grosser } 1762edb885cbSTobias Grosser 176332837fe3STobias Grosser return FN; 176432837fe3STobias Grosser } 176532837fe3STobias Grosser 1766472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 176717f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 176817f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1769472f9654STobias Grosser 177017f01968SSiddharth Bhat switch (Arch) { 177117f01968SSiddharth Bhat case GPUArch::NVPTX64: 177217f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 177317f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 177417f01968SSiddharth Bhat 177517f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 177617f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 177717f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 177817f01968SSiddharth Bhat break; 177917f01968SSiddharth Bhat } 1780472f9654STobias Grosser 1781472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1782472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1783472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1784472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1785472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1786472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1787472f9654STobias Grosser IDToValue[Id] = Val; 1788472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1789472f9654STobias Grosser }; 1790472f9654STobias Grosser 1791472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1792472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1793472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1794472f9654STobias Grosser } 1795472f9654STobias Grosser 1796472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1797472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1798472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1799472f9654STobias Grosser } 1800472f9654STobias Grosser } 1801472f9654STobias Grosser 180200bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 180300bb5a99STobias Grosser auto Arg = FN->arg_begin(); 180400bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 180500bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 180600bb5a99STobias Grosser continue; 180700bb5a99STobias Grosser 180800bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 180900bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 181000bb5a99STobias Grosser isl_id_free(Id); 181100bb5a99STobias Grosser 181200bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 181300bb5a99STobias Grosser Arg++; 181400bb5a99STobias Grosser continue; 181500bb5a99STobias Grosser } 181600bb5a99STobias Grosser 1817fe74a7a1STobias Grosser Value *Val = &*Arg; 1818fe74a7a1STobias Grosser 1819fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 182000bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 1821fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1822fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 1823fe74a7a1STobias Grosser } 1824fe74a7a1STobias Grosser 1825fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 182600bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 182700bb5a99STobias Grosser 182800bb5a99STobias Grosser Arg++; 182900bb5a99STobias Grosser } 183000bb5a99STobias Grosser } 183100bb5a99STobias Grosser 183251dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 183351dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 183451dfc275STobias Grosser auto Arg = FN->arg_begin(); 183551dfc275STobias Grosser 183651dfc275STobias Grosser bool StoredScalar = false; 183751dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 183851dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 183951dfc275STobias Grosser continue; 184051dfc275STobias Grosser 184151dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 184251dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 184351dfc275STobias Grosser isl_id_free(Id); 184451dfc275STobias Grosser 184551dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 184651dfc275STobias Grosser Arg++; 184751dfc275STobias Grosser continue; 184851dfc275STobias Grosser } 184951dfc275STobias Grosser 185051dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 185151dfc275STobias Grosser Arg++; 185251dfc275STobias Grosser continue; 185351dfc275STobias Grosser } 185451dfc275STobias Grosser 185551dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 185651dfc275STobias Grosser Value *ArgPtr = &*Arg; 185751dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 185851dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 185951dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 186051dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 186151dfc275STobias Grosser StoredScalar = true; 186251dfc275STobias Grosser 186351dfc275STobias Grosser Arg++; 186451dfc275STobias Grosser } 186551dfc275STobias Grosser 186651dfc275STobias Grosser if (StoredScalar) 186751dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 186851dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 186951dfc275STobias Grosser /// To support this case we need to store these scalars back at each 187051dfc275STobias Grosser /// memory store or at least before each kernel barrier. 187151dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 187251dfc275STobias Grosser BuildSuccessful = 0; 187351dfc275STobias Grosser } 187451dfc275STobias Grosser 1875b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1876b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1877b513b491STobias Grosser 1878b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 1879b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 1880b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1881b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1882b513b491STobias Grosser 1883f919d8b3STobias Grosser Type *ArrayTy = EleTy; 1884b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 1885b513b491STobias Grosser 1886f5aff704SRoman Gareev Sizes.push_back(nullptr); 1887928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1888b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1889f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 1890b513b491STobias Grosser isl_val_free(Val); 1891b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1892928d7573STobias Grosser } 1893928d7573STobias Grosser 1894928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 1895928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 1896928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 1897928d7573STobias Grosser isl_val_free(Val); 1898b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 1899b513b491STobias Grosser } 1900b513b491STobias Grosser 1901130ca30fSTobias Grosser const ScopArrayInfo *SAI; 1902130ca30fSTobias Grosser Value *Allocation; 1903130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 1904130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 1905130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1906130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1907130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1908f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1909f919d8b3STobias Grosser 1910130ca30fSTobias Grosser Allocation = GlobalVar; 1911130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 1912130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1913130ca30fSTobias Grosser } else { 1914130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 1915130ca30fSTobias Grosser } 19164d5a9172STobias Grosser SAI = 19174d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1918b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1919130ca30fSTobias Grosser IDToValue[Id] = Allocation; 1920130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 1921b513b491STobias Grosser KernelIds.push_back(Id); 1922b513b491STobias Grosser IDToSAI[Id] = SAI; 1923b513b491STobias Grosser } 1924b513b491STobias Grosser } 1925b513b491STobias Grosser 1926f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 1927f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 1928f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 192932837fe3STobias Grosser std::string Identifier = "kernel_" + std::to_string(Kernel->id); 193032837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 193117f01968SSiddharth Bhat 193217f01968SSiddharth Bhat switch (Arch) { 193317f01968SSiddharth Bhat case GPUArch::NVPTX64: 193417f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 193532837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 193617f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 193717f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 193832837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 193917f01968SSiddharth Bhat break; 194017f01968SSiddharth Bhat } 194132837fe3STobias Grosser 1942edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 194332837fe3STobias Grosser 194459ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 194532837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 194632837fe3STobias Grosser 194759ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 194859ab0705STobias Grosser 194932837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 195032837fe3STobias Grosser Builder.CreateRetVoid(); 195132837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1952472f9654STobias Grosser 1953629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 1954629109b6STobias Grosser 195500bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 1956b513b491STobias Grosser createKernelVariables(Kernel, FN); 1957472f9654STobias Grosser insertKernelIntrinsics(Kernel); 195832837fe3STobias Grosser } 195932837fe3STobias Grosser 196074dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 196117f01968SSiddharth Bhat llvm::Triple GPUTriple; 196217f01968SSiddharth Bhat 196317f01968SSiddharth Bhat switch (Arch) { 196417f01968SSiddharth Bhat case GPUArch::NVPTX64: 196517f01968SSiddharth Bhat switch (Runtime) { 196617f01968SSiddharth Bhat case GPURuntime::CUDA: 196717f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 196817f01968SSiddharth Bhat break; 196917f01968SSiddharth Bhat case GPURuntime::OpenCL: 197017f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 197117f01968SSiddharth Bhat break; 197217f01968SSiddharth Bhat } 197317f01968SSiddharth Bhat break; 197417f01968SSiddharth Bhat } 197517f01968SSiddharth Bhat 197674dc3cb4STobias Grosser std::string ErrMsg; 197774dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 197874dc3cb4STobias Grosser 197974dc3cb4STobias Grosser if (!GPUTarget) { 198074dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 198174dc3cb4STobias Grosser return ""; 198274dc3cb4STobias Grosser } 198374dc3cb4STobias Grosser 198474dc3cb4STobias Grosser TargetOptions Options; 198574dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 198617f01968SSiddharth Bhat 198717f01968SSiddharth Bhat std::string subtarget; 198817f01968SSiddharth Bhat 198917f01968SSiddharth Bhat switch (Arch) { 199017f01968SSiddharth Bhat case GPUArch::NVPTX64: 199117f01968SSiddharth Bhat subtarget = CudaVersion; 199217f01968SSiddharth Bhat break; 199317f01968SSiddharth Bhat } 199417f01968SSiddharth Bhat 199517f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 199617f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 199774dc3cb4STobias Grosser 199874dc3cb4STobias Grosser SmallString<0> ASMString; 199974dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 200074dc3cb4STobias Grosser llvm::legacy::PassManager PM; 200174dc3cb4STobias Grosser 200274dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 200374dc3cb4STobias Grosser 200474dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 200574dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 200674dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 200774dc3cb4STobias Grosser return ""; 200874dc3cb4STobias Grosser } 200974dc3cb4STobias Grosser 201074dc3cb4STobias Grosser PM.run(*GPUModule); 201174dc3cb4STobias Grosser 201274dc3cb4STobias Grosser return ASMStream.str(); 201374dc3cb4STobias Grosser } 201474dc3cb4STobias Grosser 201557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 201665d7f72fSSiddharth Bhat 20175857b701STobias Grosser if (verifyModule(*GPUModule)) { 201865d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 201965d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 202065d7f72fSSiddharth Bhat 202165d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 202265d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 202365d7f72fSSiddharth Bhat 20245857b701STobias Grosser BuildSuccessful = false; 20255857b701STobias Grosser return ""; 20265857b701STobias Grosser } 202732837fe3STobias Grosser 202832837fe3STobias Grosser if (DumpKernelIR) 202932837fe3STobias Grosser outs() << *GPUModule << "\n"; 203032837fe3STobias Grosser 20319a18d559STobias Grosser // Optimize module. 20329a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 20339a18d559STobias Grosser PassManagerBuilder PassBuilder; 20349a18d559STobias Grosser PassBuilder.OptLevel = 3; 20359a18d559STobias Grosser PassBuilder.SizeLevel = 0; 20369a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 20379a18d559STobias Grosser OptPasses.run(*GPUModule); 20389a18d559STobias Grosser 203974dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 204074dc3cb4STobias Grosser 204174dc3cb4STobias Grosser if (DumpKernelASM) 204274dc3cb4STobias Grosser outs() << Assembly << "\n"; 204374dc3cb4STobias Grosser 204432837fe3STobias Grosser GPUModule.release(); 2045472f9654STobias Grosser KernelIDs.clear(); 204657793596STobias Grosser 204757793596STobias Grosser return Assembly; 204832837fe3STobias Grosser } 204932837fe3STobias Grosser 20509dfe4e7cSTobias Grosser namespace { 20519dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 20529dfe4e7cSTobias Grosser public: 20539dfe4e7cSTobias Grosser static char ID; 20549dfe4e7cSTobias Grosser 205517f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 205617f01968SSiddharth Bhat 205717f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 205817f01968SSiddharth Bhat 2059e938517eSTobias Grosser /// The scop that is currently processed. 2060e938517eSTobias Grosser Scop *S; 2061e938517eSTobias Grosser 206238fc0aedSTobias Grosser LoopInfo *LI; 206338fc0aedSTobias Grosser DominatorTree *DT; 206438fc0aedSTobias Grosser ScalarEvolution *SE; 206538fc0aedSTobias Grosser const DataLayout *DL; 206638fc0aedSTobias Grosser RegionInfo *RI; 206738fc0aedSTobias Grosser 20689dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 20699dfe4e7cSTobias Grosser 2070e938517eSTobias Grosser /// Construct compilation options for PPCG. 2071e938517eSTobias Grosser /// 2072e938517eSTobias Grosser /// @returns The compilation options. 2073e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2074e938517eSTobias Grosser auto DebugOptions = 2075e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2076e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2077e938517eSTobias Grosser 2078e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2079e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2080e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2081e938517eSTobias Grosser DebugOptions->dump_sizes = false; 20828950ceadSTobias Grosser DebugOptions->verbose = false; 2083e938517eSTobias Grosser 2084e938517eSTobias Grosser Options->debug = DebugOptions; 2085e938517eSTobias Grosser 2086e938517eSTobias Grosser Options->reschedule = true; 2087e938517eSTobias Grosser Options->scale_tile_loops = false; 2088e938517eSTobias Grosser Options->wrap = false; 2089e938517eSTobias Grosser 2090e938517eSTobias Grosser Options->non_negative_parameters = false; 2091e938517eSTobias Grosser Options->ctx = nullptr; 2092e938517eSTobias Grosser Options->sizes = nullptr; 2093e938517eSTobias Grosser 20944eaedde5STobias Grosser Options->tile_size = 32; 20954eaedde5STobias Grosser 2096130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2097b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2098b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2099e938517eSTobias Grosser 2100e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2101e938517eSTobias Grosser Options->openmp = false; 2102e938517eSTobias Grosser Options->linearize_device_arrays = true; 2103e938517eSTobias Grosser Options->live_range_reordering = false; 2104e938517eSTobias Grosser 2105e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2106e938517eSTobias Grosser Options->opencl_use_gpu = false; 2107e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2108e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2109e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2110e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2111e938517eSTobias Grosser 2112e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2113e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2114e938517eSTobias Grosser 2115e938517eSTobias Grosser return Options; 2116e938517eSTobias Grosser } 2117e938517eSTobias Grosser 2118f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2119f384594dSTobias Grosser /// 2120f384594dSTobias Grosser /// Instead of a normal access of the form: 2121f384594dSTobias Grosser /// 2122f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2123f384594dSTobias Grosser /// 2124f384594dSTobias Grosser /// a tagged access has the form 2125f384594dSTobias Grosser /// 2126f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2127f384594dSTobias Grosser /// 2128f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2129f384594dSTobias Grosser /// triggered the access. 2130f384594dSTobias Grosser /// 2131f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2132f384594dSTobias Grosser /// 2133f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2134f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2135f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2136f384594dSTobias Grosser 2137f384594dSTobias Grosser for (auto &Stmt : *S) 2138f384594dSTobias Grosser for (auto &Acc : Stmt) 2139f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 2140f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 2141f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2142f384594dSTobias Grosser 2143f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2144f384594dSTobias Grosser Space = isl_space_range(Space); 2145f384594dSTobias Grosser Space = isl_space_from_range(Space); 21466293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2147f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2148f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2149f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2150f384594dSTobias Grosser } 2151f384594dSTobias Grosser 2152f384594dSTobias Grosser return Accesses; 2153f384594dSTobias Grosser } 2154f384594dSTobias Grosser 2155f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2156f384594dSTobias Grosser /// 2157f384594dSTobias Grosser /// @see getTaggedAccesses 2158f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2159f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2160f384594dSTobias Grosser } 2161f384594dSTobias Grosser 2162f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2163f384594dSTobias Grosser /// 2164f384594dSTobias Grosser /// @see getTaggedAccesses 2165f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2166f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2167f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2168f384594dSTobias Grosser } 2169f384594dSTobias Grosser 2170f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2171f384594dSTobias Grosser /// 2172f384594dSTobias Grosser /// @see getTaggedAccesses 2173f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2174f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2175f384594dSTobias Grosser } 2176f384594dSTobias Grosser 2177aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2178aef5196fSTobias Grosser /// 2179aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2180aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2181aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2182aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2183aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2184aef5196fSTobias Grosser /// the data format that ppcg expects. 2185aef5196fSTobias Grosser /// 2186aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2187aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2188aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2189bd81a7eeSTobias Grosser S->getIslCtx(), 2190bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2191aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2192aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 2193aef5196fSTobias Grosser 2194aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2195aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2196aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2197aef5196fSTobias Grosser } 2198aef5196fSTobias Grosser 2199aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 2200d7754a12SRoman Gareev auto Id = Array->getBasePtrId(); 2201aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2202aef5196fSTobias Grosser } 2203aef5196fSTobias Grosser 2204aef5196fSTobias Grosser isl_space_free(Space); 2205aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2206aef5196fSTobias Grosser 2207aef5196fSTobias Grosser return Names; 2208aef5196fSTobias Grosser } 2209aef5196fSTobias Grosser 2210e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2211e938517eSTobias Grosser /// 2212f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2213f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2214f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2215f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2216e938517eSTobias Grosser /// 2217e938517eSTobias Grosser /// @returns A new ppcg scop. 2218e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 2219e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2220e938517eSTobias Grosser 2221e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2222*a82f2d26SSiddharth Bhat // enable live range reordering 2223*a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2224e938517eSTobias Grosser 2225e938517eSTobias Grosser PPCGScop->start = 0; 2226e938517eSTobias Grosser PPCGScop->end = 0; 2227e938517eSTobias Grosser 2228f384594dSTobias Grosser PPCGScop->context = S->getContext(); 2229f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 2230e938517eSTobias Grosser PPCGScop->call = nullptr; 2231f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 2232f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 2233e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2234f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2235f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 2236f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2237f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 2238e938517eSTobias Grosser PPCGScop->live_out = nullptr; 2239e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2240*a82f2d26SSiddharth Bhat PPCGScop->independence = 2241*a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2242e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2243e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2244e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2245e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2246e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2247e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2248e938517eSTobias Grosser 2249f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2250e938517eSTobias Grosser 2251*a82f2d26SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2252*a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2253*a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2254*a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2255*a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2256*a82f2d26SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2257*a82f2d26SSiddharth Bhat 2258*a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2259e938517eSTobias Grosser PPCGScop->pet = nullptr; 2260e938517eSTobias Grosser 2261f384594dSTobias Grosser compute_tagger(PPCGScop); 2262f384594dSTobias Grosser compute_dependences(PPCGScop); 2263f384594dSTobias Grosser 2264e938517eSTobias Grosser return PPCGScop; 2265e938517eSTobias Grosser } 2266e938517eSTobias Grosser 2267a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 226860f63b49STobias Grosser /// 226960f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 227060f63b49STobias Grosser /// 227160f63b49STobias Grosser /// @returns A list of array accesses. 227260f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 227360f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 227460f63b49STobias Grosser 227560f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 227660f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 227760f63b49STobias Grosser Access->read = Acc->isRead(); 227860f63b49STobias Grosser Access->write = Acc->isWrite(); 227960f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 228060f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 228160f63b49STobias Grosser Space = isl_space_range(Space); 228260f63b49STobias Grosser Space = isl_space_from_range(Space); 22836293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 228460f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 228560f63b49STobias Grosser Access->tagged_access = 228660f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2287b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 228860f63b49STobias Grosser Access->ref_id = Acc->getId(); 228960f63b49STobias Grosser Access->next = Accesses; 2290b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 229160f63b49STobias Grosser Accesses = Access; 229260f63b49STobias Grosser } 229360f63b49STobias Grosser 229460f63b49STobias Grosser return Accesses; 229560f63b49STobias Grosser } 229660f63b49STobias Grosser 229769b46751STobias Grosser /// Collect the list of GPU statements. 229869b46751STobias Grosser /// 229969b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 230069b46751STobias Grosser /// as well as a list with all memory accesses. 230169b46751STobias Grosser /// 230269b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 230369b46751STobias Grosser /// 230469b46751STobias Grosser /// @returns A linked-list of statements. 230569b46751STobias Grosser gpu_stmt *getStatements() { 230669b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 230769b46751STobias Grosser std::distance(S->begin(), S->end())); 230869b46751STobias Grosser 230969b46751STobias Grosser int i = 0; 231069b46751STobias Grosser for (auto &Stmt : *S) { 231169b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 231269b46751STobias Grosser 231369b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 231469b46751STobias Grosser 231569b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 231669b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 231760f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 231869b46751STobias Grosser i++; 231969b46751STobias Grosser } 232069b46751STobias Grosser 232169b46751STobias Grosser return Stmts; 232269b46751STobias Grosser } 232369b46751STobias Grosser 232460f63b49STobias Grosser /// Derive the extent of an array. 232560f63b49STobias Grosser /// 2326d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2327d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2328d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2329d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2330d58acf86STobias Grosser /// subscript value for the first dimension. 233160f63b49STobias Grosser /// 233260f63b49STobias Grosser /// @param Array The array to derive the extent for. 233360f63b49STobias Grosser /// 233460f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 233560f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2336d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 233760f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 233860f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2339d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 234060f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2341d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2342d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2343d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2344d58acf86STobias Grosser 2345d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2346d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2347d58acf86STobias Grosser return isl_set_empty(Array->getSpace()); 2348d58acf86STobias Grosser } 2349d58acf86STobias Grosser 2350d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2351d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2352d58acf86STobias Grosser return isl_set_universe(Array->getSpace()); 2353d58acf86STobias Grosser } 2354d58acf86STobias Grosser 235560f63b49STobias Grosser isl_set *AccessSet = 235660f63b49STobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace()); 235760f63b49STobias Grosser 2358d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2359d58acf86STobias Grosser isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2360d58acf86STobias Grosser 2361d58acf86STobias Grosser isl_pw_aff *Val = 2362d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2363d58acf86STobias Grosser 2364d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2365d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2366d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2367d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2368d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2369d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2370d58acf86STobias Grosser OuterMin = 2371d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2372d58acf86STobias Grosser OuterMax = 2373d58acf86STobias Grosser isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2374d58acf86STobias Grosser 2375d58acf86STobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace()); 2376d58acf86STobias Grosser 2377d58acf86STobias Grosser Extent = isl_set_intersect( 2378d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2379d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2380d58acf86STobias Grosser 2381d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2382d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2383d58acf86STobias Grosser 2384b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2385d58acf86STobias Grosser isl_pw_aff *PwAff = 2386d58acf86STobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2387b7f68b8cSSiddharth Bhat 2388b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2389b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2390b7f68b8cSSiddharth Bhat if (!PwAff) { 2391b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2392b7f68b8cSSiddharth Bhat continue; 2393b7f68b8cSSiddharth Bhat } 2394b7f68b8cSSiddharth Bhat 2395d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2396d58acf86STobias Grosser isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2397d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2398d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2399d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2400d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2401d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2402d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2403d58acf86STobias Grosser } 2404d58acf86STobias Grosser 2405d58acf86STobias Grosser return Extent; 240660f63b49STobias Grosser } 240760f63b49STobias Grosser 240860f63b49STobias Grosser /// Derive the bounds of an array. 240960f63b49STobias Grosser /// 241060f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 241160f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 241260f63b49STobias Grosser /// ScopArrayInfo. 241360f63b49STobias Grosser /// 241460f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 241560f63b49STobias Grosser /// @param Array The polly array from which to take the information. 241660f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 241760f63b49STobias Grosser if (PPCGArray.n_index > 0) { 241802293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 241902293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 242002293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 242102293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 242202293ed7STobias Grosser isl_set_free(Dom); 242302293ed7STobias Grosser isl_aff *Zero = isl_aff_zero_on_domain(LS); 242402293ed7STobias Grosser PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 242502293ed7STobias Grosser } else { 242660f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 242760f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 242860f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 242960f63b49STobias Grosser isl_set_free(Dom); 243060f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 243102293ed7STobias Grosser isl_local_space *LS = 243202293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 243360f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 243460f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 243560f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 243660f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 243760f63b49STobias Grosser PPCGArray.bound[0] = Bound; 243860f63b49STobias Grosser } 243902293ed7STobias Grosser } 244060f63b49STobias Grosser 244160f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 244260f63b49STobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i); 244360f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 244460f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 244560f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 244660f63b49STobias Grosser PPCGArray.bound[i] = Bound; 244760f63b49STobias Grosser } 244860f63b49STobias Grosser } 244960f63b49STobias Grosser 245060f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 245160f63b49STobias Grosser /// 245260f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 245360f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 245460f63b49STobias Grosser int i = 0; 2455d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 245660f63b49STobias Grosser std::string TypeName; 245760f63b49STobias Grosser raw_string_ostream OS(TypeName); 245860f63b49STobias Grosser 245960f63b49STobias Grosser OS << *Array->getElementType(); 246060f63b49STobias Grosser TypeName = OS.str(); 246160f63b49STobias Grosser 246260f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 246360f63b49STobias Grosser 246460f63b49STobias Grosser PPCGArray.space = Array->getSpace(); 246560f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 246660f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 246760f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 246860f63b49STobias Grosser PPCGArray.extent = nullptr; 246960f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 247060f63b49STobias Grosser PPCGArray.bound = 247160f63b49STobias Grosser isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 247260f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 247360f63b49STobias Grosser PPCGArray.n_ref = 0; 247460f63b49STobias Grosser PPCGArray.refs = nullptr; 247560f63b49STobias Grosser PPCGArray.accessed = true; 2476fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2477fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 247860f63b49STobias Grosser PPCGArray.has_compound_element = false; 247960f63b49STobias Grosser PPCGArray.local = false; 248060f63b49STobias Grosser PPCGArray.declare_local = false; 248160f63b49STobias Grosser PPCGArray.global = false; 248260f63b49STobias Grosser PPCGArray.linearize = false; 248360f63b49STobias Grosser PPCGArray.dep_order = nullptr; 248413c78e4dSTobias Grosser PPCGArray.user = Array; 248560f63b49STobias Grosser 248660f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 24872d010dafSTobias Grosser i++; 2488b9fc860aSTobias Grosser 2489b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 249060f63b49STobias Grosser } 249160f63b49STobias Grosser } 249260f63b49STobias Grosser 249360f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 249460f63b49STobias Grosser /// 249560f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 249660f63b49STobias Grosser isl_union_map *getArrayIdentity() { 249760f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 249860f63b49STobias Grosser 2499d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 250060f63b49STobias Grosser isl_space *Space = Array->getSpace(); 250160f63b49STobias Grosser Space = isl_space_map_from_set(Space); 250260f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 250360f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 250460f63b49STobias Grosser } 250560f63b49STobias Grosser 250660f63b49STobias Grosser return Maps; 250760f63b49STobias Grosser } 250860f63b49STobias Grosser 2509e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2510e938517eSTobias Grosser /// 2511a6d48f59SMichael Kruse /// @returns A new gpu program description. 2512e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2513e938517eSTobias Grosser 2514e938517eSTobias Grosser if (!PPCGScop) 2515e938517eSTobias Grosser return nullptr; 2516e938517eSTobias Grosser 2517e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2518e938517eSTobias Grosser 2519e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2520e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2521aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 252260f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 252360f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 252460f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 252560f63b49STobias Grosser PPCGProg->tagged_must_kill = 252660f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 252760f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 252860f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 2529e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2530*a82f2d26SSiddharth Bhat 2531*a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2532*a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2533*a82f2d26SSiddharth Bhat // what the semantics of this is. 2534*a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2535*a82f2d26SSiddharth Bhat PPCGProg->array_order = 2536*a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 253769b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 253869b46751STobias Grosser PPCGProg->stmts = getStatements(); 253960f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 254060f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 254160f63b49STobias Grosser PPCGProg->n_array); 254260f63b49STobias Grosser 254360f63b49STobias Grosser createArrays(PPCGProg); 2544e938517eSTobias Grosser 2545d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2546e938517eSTobias Grosser return PPCGProg; 2547e938517eSTobias Grosser } 2548e938517eSTobias Grosser 254969b46751STobias Grosser struct PrintGPUUserData { 255069b46751STobias Grosser struct cuda_info *CudaInfo; 255169b46751STobias Grosser struct gpu_prog *PPCGProg; 255269b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 255369b46751STobias Grosser }; 255469b46751STobias Grosser 255569b46751STobias Grosser /// Print a user statement node in the host code. 255669b46751STobias Grosser /// 255769b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 255869b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 255969b46751STobias Grosser /// host ast. 256069b46751STobias Grosser /// 256169b46751STobias Grosser /// @param P The printer to print to 256269b46751STobias Grosser /// @param Options The printing options to use 256369b46751STobias Grosser /// @param Node The node to print 256469b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 256569b46751STobias Grosser /// expected to be of type PrintGPUUserData. 256669b46751STobias Grosser /// 256769b46751STobias Grosser /// @returns A printer to which the output has been printed. 256869b46751STobias Grosser static __isl_give isl_printer * 256969b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 257069b46751STobias Grosser __isl_take isl_ast_print_options *Options, 257169b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 257269b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 257369b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 257469b46751STobias Grosser 257569b46751STobias Grosser if (Id) { 257620251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 257720251734STobias Grosser 257820251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 257920251734STobias Grosser // otherwise try to call pet functionality that is not available in 258020251734STobias Grosser // Polly. 258120251734STobias Grosser if (IsUser) { 258220251734STobias Grosser P = isl_printer_start_line(P); 258320251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 258420251734STobias Grosser P = isl_printer_end_line(P); 258520251734STobias Grosser isl_id_free(Id); 258620251734STobias Grosser isl_ast_print_options_free(Options); 258720251734STobias Grosser return P; 258820251734STobias Grosser } 258920251734STobias Grosser 259069b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 259169b46751STobias Grosser isl_id_free(Id); 259269b46751STobias Grosser Data->Kernels.push_back(Kernel); 259369b46751STobias Grosser } 259469b46751STobias Grosser 259569b46751STobias Grosser return print_host_user(P, Options, Node, User); 259669b46751STobias Grosser } 259769b46751STobias Grosser 259869b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 259969b46751STobias Grosser /// 260069b46751STobias Grosser /// @param Kernel The kernel to print 260169b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 260269b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 260369b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 260469b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 260569b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 260669b46751STobias Grosser char *String = isl_printer_get_str(P); 260769b46751STobias Grosser printf("%s\n", String); 260869b46751STobias Grosser free(String); 260969b46751STobias Grosser isl_printer_free(P); 261069b46751STobias Grosser } 261169b46751STobias Grosser 261269b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 261369b46751STobias Grosser /// 261469b46751STobias Grosser /// @param Tree An AST describing GPU code 261569b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 261669b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 261769b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 261869b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 261969b46751STobias Grosser 262069b46751STobias Grosser PrintGPUUserData Data; 262169b46751STobias Grosser Data.PPCGProg = PPCGProg; 262269b46751STobias Grosser 262369b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 262469b46751STobias Grosser Options = 262569b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 262669b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 262769b46751STobias Grosser char *String = isl_printer_get_str(P); 262869b46751STobias Grosser printf("# host\n"); 262969b46751STobias Grosser printf("%s\n", String); 263069b46751STobias Grosser free(String); 263169b46751STobias Grosser isl_printer_free(P); 263269b46751STobias Grosser 263369b46751STobias Grosser for (auto Kernel : Data.Kernels) { 263469b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 263569b46751STobias Grosser printKernel(Kernel); 263669b46751STobias Grosser } 263769b46751STobias Grosser } 263869b46751STobias Grosser 2639f384594dSTobias Grosser // Generate a GPU program using PPCG. 2640f384594dSTobias Grosser // 2641f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2642f384594dSTobias Grosser // 2643f384594dSTobias Grosser // 1) Compute new schedule for the program. 2644f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2645f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2646f384594dSTobias Grosser // 2647f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2648f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2649f384594dSTobias Grosser // strategy directly from this pass. 2650f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2651f384594dSTobias Grosser 2652f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2653f384594dSTobias Grosser 2654f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2655f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2656f384594dSTobias Grosser PPCGGen->print = nullptr; 2657f384594dSTobias Grosser PPCGGen->print_user = nullptr; 265860c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2659f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2660f384594dSTobias Grosser PPCGGen->tree = nullptr; 2661f384594dSTobias Grosser PPCGGen->types.n = 0; 2662f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2663f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2664f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2665f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2666f384594dSTobias Grosser 2667f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2668f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2669f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 26702341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2671f384594dSTobias Grosser 2672f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2673f384594dSTobias Grosser 2674aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2675aef5196fSTobias Grosser 267669b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2677aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 267869b46751STobias Grosser } else { 2679aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 268069b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 268169b46751STobias Grosser } 2682aef5196fSTobias Grosser 2683f384594dSTobias Grosser if (DumpSchedule) { 2684f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2685f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2686f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2687f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2688f384594dSTobias Grosser if (Schedule) 2689f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2690f384594dSTobias Grosser else 2691f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2692f384594dSTobias Grosser 2693f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2694f384594dSTobias Grosser isl_printer_free(P); 2695f384594dSTobias Grosser } 2696f384594dSTobias Grosser 269769b46751STobias Grosser if (DumpCode) { 269869b46751STobias Grosser printf("Code\n"); 269969b46751STobias Grosser printf("====\n"); 270069b46751STobias Grosser if (PPCGGen->tree) 270169b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 270269b46751STobias Grosser else 270369b46751STobias Grosser printf("No code generated\n"); 270469b46751STobias Grosser } 270569b46751STobias Grosser 2706f384594dSTobias Grosser isl_schedule_free(Schedule); 2707f384594dSTobias Grosser 2708f384594dSTobias Grosser return PPCGGen; 2709f384594dSTobias Grosser } 2710f384594dSTobias Grosser 2711f384594dSTobias Grosser /// Free gpu_gen structure. 2712f384594dSTobias Grosser /// 2713f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2714f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2715f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2716f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2717f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2718f384594dSTobias Grosser free(PPCGGen); 2719f384594dSTobias Grosser } 2720f384594dSTobias Grosser 2721b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2722b307ed4dSTobias Grosser /// 2723b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2724b307ed4dSTobias Grosser /// ourselves. 2725b307ed4dSTobias Grosser /// 2726b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2727b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2728b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2729b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2730b307ed4dSTobias Grosser free(PPCGScop->options); 2731b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2732b307ed4dSTobias Grosser } 2733b307ed4dSTobias Grosser 273482f2af35STobias Grosser /// Approximate the number of points in the set. 273582f2af35STobias Grosser /// 273682f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 273782f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 273882f2af35STobias Grosser /// 273982f2af35STobias Grosser /// @param Set The set to count. 274082f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 274182f2af35STobias Grosser /// expression. 274282f2af35STobias Grosser /// 274382f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 274482f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 274582f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 274682f2af35STobias Grosser 274782f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 274882f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 274982f2af35STobias Grosser 275082f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 275182f2af35STobias Grosser Space = isl_space_params(Space); 275282f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 275382f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 275482f2af35STobias Grosser 275582f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 275682f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 275782f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 275882f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 275982f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 276082f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 276182f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 276282f2af35STobias Grosser } 276382f2af35STobias Grosser 276482f2af35STobias Grosser isl_set_free(Set); 276582f2af35STobias Grosser isl_pw_aff_free(OneAff); 276682f2af35STobias Grosser 276782f2af35STobias Grosser return Expr; 276882f2af35STobias Grosser } 276982f2af35STobias Grosser 277082f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 277182f2af35STobias Grosser /// statement. 277282f2af35STobias Grosser /// 277382f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 277482f2af35STobias Grosser /// instructions. 277582f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 277682f2af35STobias Grosser /// expression. 277782f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 277882f2af35STobias Grosser /// by @p Stmt. 277982f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 278082f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 278182f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 278282f2af35STobias Grosser 278382f2af35STobias Grosser long InstCount = 0; 278482f2af35STobias Grosser 278582f2af35STobias Grosser if (Stmt.isBlockStmt()) { 278682f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 278782f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 278882f2af35STobias Grosser } else { 278982f2af35STobias Grosser auto *R = Stmt.getRegion(); 279082f2af35STobias Grosser 279182f2af35STobias Grosser for (auto *BB : R->blocks()) { 279282f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 279382f2af35STobias Grosser } 279482f2af35STobias Grosser } 279582f2af35STobias Grosser 279682f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 279782f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 279882f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 279982f2af35STobias Grosser } 280082f2af35STobias Grosser 280182f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 280282f2af35STobias Grosser /// 280382f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 280482f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 280582f2af35STobias Grosser /// expression. 280682f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 280782f2af35STobias Grosser /// in @p S. 280882f2af35STobias Grosser __isl_give isl_ast_expr * 280982f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 281082f2af35STobias Grosser isl_ast_expr *Instructions; 281182f2af35STobias Grosser 281282f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 281382f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 281482f2af35STobias Grosser 281582f2af35STobias Grosser for (ScopStmt &Stmt : S) { 281682f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 281782f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 281882f2af35STobias Grosser } 281982f2af35STobias Grosser return Instructions; 282082f2af35STobias Grosser } 282182f2af35STobias Grosser 282282f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 282382f2af35STobias Grosser /// 282482f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 282582f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 282682f2af35STobias Grosser /// expression. 282782f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 282882f2af35STobias Grosser /// compute and to FALSE, otherwise. 282982f2af35STobias Grosser __isl_give isl_ast_expr * 283082f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 283182f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 283282f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 283382f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 283482f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 283582f2af35STobias Grosser } 283682f2af35STobias Grosser 2837f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 2838f291c8d5SSiddharth Bhat /// kernels. 2839f291c8d5SSiddharth Bhat /// 2840f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 2841f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 2842f291c8d5SSiddharth Bhat bool containsInvalidKernelFunctionInBllock(const BasicBlock *BB) { 2843f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 2844f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 2845f291c8d5SSiddharth Bhat if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 2846f291c8d5SSiddharth Bhat continue; 2847f291c8d5SSiddharth Bhat } 2848f291c8d5SSiddharth Bhat 2849bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 2850bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 2851bccaea57SSiddharth Bhat if (!p) 2852bccaea57SSiddharth Bhat continue; 2853bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 2854bccaea57SSiddharth Bhat return true; 2855bccaea57SSiddharth Bhat } 2856f291c8d5SSiddharth Bhat } 2857bccaea57SSiddharth Bhat return false; 2858bccaea57SSiddharth Bhat } 2859bccaea57SSiddharth Bhat 2860f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 2861f291c8d5SSiddharth Bhat bool containsInvalidKernelFunction(const Scop &S) { 2862bccaea57SSiddharth Bhat for (auto &Stmt : S) { 2863bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 2864f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(Stmt.getBasicBlock())) 2865bccaea57SSiddharth Bhat return true; 2866bccaea57SSiddharth Bhat } else { 2867bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 2868bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 2869bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 2870f291c8d5SSiddharth Bhat if (containsInvalidKernelFunctionInBllock(BB)) 2871bccaea57SSiddharth Bhat return true; 2872bccaea57SSiddharth Bhat } 2873bccaea57SSiddharth Bhat } 2874bccaea57SSiddharth Bhat return false; 2875bccaea57SSiddharth Bhat } 2876bccaea57SSiddharth Bhat 287738fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 287838fc0aedSTobias Grosser /// 287932837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 288032837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 288132837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 288238fc0aedSTobias Grosser ScopAnnotator Annotator; 288338fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 288438fc0aedSTobias Grosser 288538fc0aedSTobias Grosser Region *R = &S->getRegion(); 288638fc0aedSTobias Grosser 288738fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 288838fc0aedSTobias Grosser 288938fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 289038fc0aedSTobias Grosser 289138fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 289238fc0aedSTobias Grosser 289338fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 289438fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 289538fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 289638fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 289738fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 289838fc0aedSTobias Grosser // code generating this scop. 2899256070d8SAndreas Simbuerger BBPair StartExitBlocks = 29002d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 2901256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 290238fc0aedSTobias Grosser 29032d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 290417f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 2905acf80064SEli Friedman 290638fc0aedSTobias Grosser // TODO: Handle LICM 290738fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 290838fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 290938fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 2910cb1aef8dSTobias Grosser 2911cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 29122b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 291382f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 291482f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 2915cb1aef8dSTobias Grosser isl_ast_build_free(Build); 2916cb1aef8dSTobias Grosser 2917cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 2918cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2919cb1aef8dSTobias Grosser 292038fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 2921fa7b0802STobias Grosser 2922fa7b0802STobias Grosser NodeBuilder.initializeAfterRTH(); 292338fc0aedSTobias Grosser NodeBuilder.create(Root); 29248ed5e599STobias Grosser NodeBuilder.finalize(); 29255857b701STobias Grosser 2926bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 2927bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2928de244eb4STobias Grosser /// point in running it on a GPU. 2929bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 2930bc653f20STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 2931bc653f20STobias Grosser 29325857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 29335857b701STobias Grosser SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 293438fc0aedSTobias Grosser } 293538fc0aedSTobias Grosser 2936e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 2937e938517eSTobias Grosser S = &CurrentScop; 293838fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 293938fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 294038fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 29417b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 294238fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2943e938517eSTobias Grosser 2944f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 2945f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 2946f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 2947bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 2948bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 2949f291c8d5SSiddharth Bhat if (containsInvalidKernelFunction(CurrentScop)) { 2950f291c8d5SSiddharth Bhat DEBUG( 2951f291c8d5SSiddharth Bhat dbgs() 2952f291c8d5SSiddharth Bhat << "Scop contains function which cannot be materialised in a GPU " 2953f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 2954bccaea57SSiddharth Bhat return false; 2955f291c8d5SSiddharth Bhat } 2956bccaea57SSiddharth Bhat 2957e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 2958e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 2959f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 296038fc0aedSTobias Grosser 296102ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 296232837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 296302ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 296402ca346eSSingapuram Sanjay Srivallabh } 296538fc0aedSTobias Grosser 2966b307ed4dSTobias Grosser freeOptions(PPCGScop); 2967f384594dSTobias Grosser freePPCGGen(PPCGGen); 2968e938517eSTobias Grosser gpu_prog_free(PPCGProg); 2969e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 2970e938517eSTobias Grosser 2971e938517eSTobias Grosser return true; 2972e938517eSTobias Grosser } 29739dfe4e7cSTobias Grosser 29749dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 29759dfe4e7cSTobias Grosser 29769dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 29779dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 29789dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 29799dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 29805cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 29819dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 29829dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 29839dfe4e7cSTobias Grosser 29849dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 29859dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 29869dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 29879dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 29889dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 29895cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 29909dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 29919dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 29929dfe4e7cSTobias Grosser 29939dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 29949dfe4e7cSTobias Grosser // region tree. 29959dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 29969dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 29979dfe4e7cSTobias Grosser } 29989dfe4e7cSTobias Grosser }; 299924222c73STobias Grosser } // namespace 30009dfe4e7cSTobias Grosser 30019dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 30029dfe4e7cSTobias Grosser 300317f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 300417f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 300517f01968SSiddharth Bhat generator->Runtime = Runtime; 300617f01968SSiddharth Bhat generator->Architecture = Arch; 300717f01968SSiddharth Bhat return generator; 300817f01968SSiddharth Bhat } 30099dfe4e7cSTobias Grosser 30109dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 30119dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 30129dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 30139dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 30149dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 30159dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 30169dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 30175cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 30189dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 30199dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3020