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" 1671dfb3ebSSiddharth Bhat #include "polly/CodeGen/CodeGeneration.h" 17cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 189dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 19*7b9f5ca2SSiddharth Bhat #include "polly/CodeGen/PerfMonitor.h" 2038fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 219dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 229dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 23f384594dSTobias Grosser #include "polly/Options.h" 24629109b6STobias Grosser #include "polly/ScopDetection.h" 259dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 26edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2774dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 309dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 319dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3274dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3374dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3474dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 35e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 368fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h" 378fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h" 3874dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3974dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 4074dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 419a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 42750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 439dfe4e7cSTobias Grosser 44f384594dSTobias Grosser #include "isl/union_map.h" 45f384594dSTobias Grosser 46e938517eSTobias Grosser extern "C" { 47a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 48a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 49a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 50a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 51a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 52e938517eSTobias Grosser } 53e938517eSTobias Grosser 549dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 559dfe4e7cSTobias Grosser 569dfe4e7cSTobias Grosser using namespace polly; 579dfe4e7cSTobias Grosser using namespace llvm; 589dfe4e7cSTobias Grosser 599dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 609dfe4e7cSTobias Grosser 61f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 62f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 63681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 64f384594dSTobias Grosser cl::cat(PollyCategory)); 6569b46751STobias Grosser 6669b46751STobias Grosser static cl::opt<bool> 6769b46751STobias Grosser DumpCode("polly-acc-dump-code", 6869b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6969b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 7069b46751STobias Grosser 7132837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 7232837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 7332837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7432837fe3STobias Grosser cl::cat(PollyCategory)); 7532837fe3STobias Grosser 7674dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7774dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7874dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7974dc3cb4STobias Grosser cl::cat(PollyCategory)); 8074dc3cb4STobias Grosser 8174dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 8274dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 8374dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8474dc3cb4STobias Grosser cl::cat(PollyCategory)); 85b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 86b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 87b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 88b513b491STobias Grosser cl::cat(PollyCategory)); 89130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 90130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 91130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 92130ca30fSTobias Grosser cl::cat(PollyCategory)); 9374dc3cb4STobias Grosser 94c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory; 95c4a4af47SSiddharth Bhat static cl::opt<bool, true> 96c4a4af47SSiddharth Bhat XManagedMemory("polly-acc-codegen-managed-memory", 97abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 98abed4969SSiddharth Bhat " that all memory has been" 99abed4969SSiddharth Bhat " declared as managed memory"), 100c4a4af47SSiddharth Bhat cl::location(PollyManagedMemory), cl::Hidden, 101c4a4af47SSiddharth Bhat cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 102abed4969SSiddharth Bhat 10365d7f72fSSiddharth Bhat static cl::opt<bool> 10465d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 10565d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10665d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10765d7f72fSSiddharth Bhat " kernel module."), 10865d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10965d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 11065d7f72fSSiddharth Bhat 1118fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice( 1128fc6cdfbSTobias Grosser "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden, 1138fc6cdfbSTobias Grosser cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"), 1148fc6cdfbSTobias Grosser cl::ZeroOrMore, cl::cat(PollyCategory)); 1158fc6cdfbSTobias Grosser 11674dc3cb4STobias Grosser static cl::opt<std::string> 11774dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 11874dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 11974dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 12074dc3cb4STobias Grosser 12182f2af35STobias Grosser static cl::opt<int> 12282f2af35STobias Grosser MinCompute("polly-acc-mincompute", 12382f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 12482f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 12582f2af35STobias Grosser 126*7b9f5ca2SSiddharth Bhat extern bool polly::PerfMonitoring; 127*7b9f5ca2SSiddharth Bhat 128638316daSSiddharth Bhat /// Return a unique name for a Scop, which is the scop region with the 129638316daSSiddharth Bhat /// function name. 130638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) { 131638316daSSiddharth Bhat return "Scop Region: " + S->getNameStr() + 132638316daSSiddharth Bhat " | Function: " + std::string(S->getFunction().getName()); 133638316daSSiddharth Bhat } 134638316daSSiddharth Bhat 135a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 136a82f2d26SSiddharth Bhat /// used by live range reordering. 137a82f2d26SSiddharth Bhat /// 138a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 139a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 140a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 141a82f2d26SSiddharth Bhat struct MustKillsInfo { 142a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 143a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 144a82f2d26SSiddharth Bhat /// 145a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 146a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 147a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 148a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 149a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 150a82f2d26SSiddharth Bhat /// killed. 151a82f2d26SSiddharth Bhat /// 152edfef5aeSSiddharth Bhat /// We currently derive kill information for: 153edfef5aeSSiddharth Bhat /// 1. phi nodes. PHI nodes are not alive outside the scop and can 154edfef5aeSSiddharth Bhat /// consequently all be killed. 155edfef5aeSSiddharth Bhat /// 2. Scalar arrays that are not used outside the Scop. This is 156edfef5aeSSiddharth Bhat /// checked by `isScalarUsesContainedInScop`. 157edfef5aeSSiddharth Bhat /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 158a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 159a82f2d26SSiddharth Bhat 1609e3db2b7SSiddharth Bhat /// Tagged must kills stripped of the tags. 1619e3db2b7SSiddharth Bhat /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 1629e3db2b7SSiddharth Bhat isl::union_map MustKills; 1639e3db2b7SSiddharth Bhat 1649e3db2b7SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr) {} 165a82f2d26SSiddharth Bhat }; 166a82f2d26SSiddharth Bhat 167761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 168761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 169761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 170761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 171761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 172761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 173761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 174761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 175761e5b93SSiddharth Bhat 176761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 177761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 178761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 179761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 180761e5b93SSiddharth Bhat if (!R.contains(I)) 181761e5b93SSiddharth Bhat return false; 182761e5b93SSiddharth Bhat } 183761e5b93SSiddharth Bhat return true; 184761e5b93SSiddharth Bhat } 185761e5b93SSiddharth Bhat 186a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 187a82f2d26SSiddharth Bhat /// 188a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 189a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 190a82f2d26SSiddharth Bhat /// PPCG. 191a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 192b65ccc43STobias Grosser const isl::space ParamSpace = S.getParamSpace(); 193a82f2d26SSiddharth Bhat MustKillsInfo Info; 194a82f2d26SSiddharth Bhat 195761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 196761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 197761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 198a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 199a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 200761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 201761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 20277eef90fSTobias Grosser KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 203a82f2d26SSiddharth Bhat } 204a82f2d26SSiddharth Bhat 205d70ea7feSTobias Grosser Info.TaggedMustKills = isl::union_map::empty(ParamSpace); 206d70ea7feSTobias Grosser Info.MustKills = isl::union_map::empty(ParamSpace); 207a82f2d26SSiddharth Bhat 208a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 209a82f2d26SSiddharth Bhat // schedule: 210a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 211a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 212a82f2d26SSiddharth Bhat // at the cost of some code complexity. 213a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 214a82f2d26SSiddharth Bhat 215edfef5aeSSiddharth Bhat for (isl::id &ToKillId : KillMemIds) { 216a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 217edfef5aeSSiddharth Bhat S.getIslCtx(), 218edfef5aeSSiddharth Bhat std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 219a82f2d26SSiddharth Bhat 220a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 221a82f2d26SSiddharth Bhat // 2. We need to construct a map: 222edfef5aeSSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 223a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 224edfef5aeSSiddharth Bhat // 2a. StmtToScalar: 225edfef5aeSSiddharth Bhat // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 226edfef5aeSSiddharth Bhat // 2b. PhantomRefToScalar: 227edfef5aeSSiddharth Bhat // [param] -> { ref_phantom[] -> scalar_to_kill[] } 228a82f2d26SSiddharth Bhat // 229a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 230a82f2d26SSiddharth Bhat // TaggedMustKill: 231edfef5aeSSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 232a82f2d26SSiddharth Bhat 233edfef5aeSSiddharth Bhat // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 234d70ea7feSTobias Grosser isl::map StmtToScalar = isl::map::universe(ParamSpace); 235edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 236edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 237a82f2d26SSiddharth Bhat 238a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 239edfef5aeSSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 240edfef5aeSSiddharth Bhat nullptr); 241a82f2d26SSiddharth Bhat 242edfef5aeSSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 243d70ea7feSTobias Grosser isl::map PhantomRefToScalar = isl::map::universe(ParamSpace); 244edfef5aeSSiddharth Bhat PhantomRefToScalar = 245edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 246edfef5aeSSiddharth Bhat PhantomRefToScalar = 247edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 248a82f2d26SSiddharth Bhat 249edfef5aeSSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 250edfef5aeSSiddharth Bhat isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 251a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 252a82f2d26SSiddharth Bhat 2539e3db2b7SSiddharth Bhat // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 2549e3db2b7SSiddharth Bhat Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 2559e3db2b7SSiddharth Bhat 256a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 257a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 258a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 259a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 260a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 261a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 262a82f2d26SSiddharth Bhat 263a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 264a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 265a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 266a82f2d26SSiddharth Bhat else 267a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 268a82f2d26SSiddharth Bhat } 269a82f2d26SSiddharth Bhat 270a82f2d26SSiddharth Bhat return Info; 271a82f2d26SSiddharth Bhat } 272a82f2d26SSiddharth Bhat 27360c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 27460c60025STobias Grosser /// 27560c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 27660c60025STobias Grosser /// of the scheduled ScopStmts. 27760c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 27835de9009SSiddharth Bhat void *StmtT, __isl_take isl_ast_build *Build_C, 27960c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 28060c60025STobias Grosser isl_id *Id, void *User), 28160c60025STobias Grosser void *UserIndex, 28260c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 283edb885cbSTobias Grosser void *UserExpr) { 28460c60025STobias Grosser 285edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 28660c60025STobias Grosser 28735de9009SSiddharth Bhat if (!Stmt || !Build_C) 288edb885cbSTobias Grosser return NULL; 289edb885cbSTobias Grosser 29035de9009SSiddharth Bhat isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C)); 29135de9009SSiddharth Bhat isl::ctx Ctx = Build.get_ctx(); 29235de9009SSiddharth Bhat isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0); 293edb885cbSTobias Grosser 294cff9696eSTobias Grosser Stmt->setAstBuild(Build); 295cff9696eSTobias Grosser 296edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 29735de9009SSiddharth Bhat isl::map AddrFunc = Acc->getAddressFunction(); 298dcf8d696STobias Grosser AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain()); 29935de9009SSiddharth Bhat 30035de9009SSiddharth Bhat isl::id RefId = Acc->getId(); 30135de9009SSiddharth Bhat isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 30235de9009SSiddharth Bhat 30335de9009SSiddharth Bhat isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 30435de9009SSiddharth Bhat MPA = MPA.coalesce(); 30535de9009SSiddharth Bhat MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 30635de9009SSiddharth Bhat 30735de9009SSiddharth Bhat isl::ast_expr Access = Build.access_from(MPA); 30835de9009SSiddharth Bhat Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 30935de9009SSiddharth Bhat RefToExpr = RefToExpr.set(RefId, Access); 310edb885cbSTobias Grosser } 311edb885cbSTobias Grosser 31235de9009SSiddharth Bhat return RefToExpr.release(); 31360c60025STobias Grosser } 314f384594dSTobias Grosser 315a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 316a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 317a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 318a90be207SSiddharth Bhat if (bytes == 0) 319a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 320a90be207SSiddharth Bhat return bytes; 321a90be207SSiddharth Bhat } 322a90be207SSiddharth Bhat 32338fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 32438fc0aedSTobias Grosser /// 32538fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 326a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 32738fc0aedSTobias Grosser /// for generating GPU specific user nodes. 32838fc0aedSTobias Grosser /// 32938fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 33038fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 33138fc0aedSTobias Grosser public: 3322d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 33338fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 334acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 33517f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3362d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 33717f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 338edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 339edb885cbSTobias Grosser } 34038fc0aedSTobias Grosser 341fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 342fa7b0802STobias Grosser void initializeAfterRTH(); 343fa7b0802STobias Grosser 344fa7b0802STobias Grosser /// Finalize the generated scop. 345fa7b0802STobias Grosser virtual void finalize(); 346fa7b0802STobias Grosser 3475857b701STobias Grosser /// Track if the full build process was successful. 3485857b701STobias Grosser /// 3495857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3505857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3515857b701STobias Grosser bool BuildSuccessful = true; 3525857b701STobias Grosser 353bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 354bc653f20STobias Grosser unsigned DeepestSequential = 0; 355bc653f20STobias Grosser 356bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 357bc653f20STobias Grosser unsigned DeepestParallel = 0; 358bc653f20STobias Grosser 35979f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 36079f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 36179f13b9aSSingapuram Sanjay Srivallabh 36238fc0aedSTobias Grosser private: 36374dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 36474dc3cb4STobias Grosser /// 36574dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 36674dc3cb4STobias Grosser /// more. 36774dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 36874dc3cb4STobias Grosser 36913c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 37013c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3717287aeddSTobias Grosser 372fa7b0802STobias Grosser /// The current GPU context. 373fa7b0802STobias Grosser Value *GPUContext; 374fa7b0802STobias Grosser 375b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 376b513b491STobias Grosser std::vector<isl_id *> KernelIds; 377b513b491STobias Grosser 37832837fe3STobias Grosser /// A module containing GPU code. 37932837fe3STobias Grosser /// 38032837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 38132837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 38232837fe3STobias Grosser 38332837fe3STobias Grosser /// The GPU program we generate code for. 38432837fe3STobias Grosser gpu_prog *Prog; 38532837fe3STobias Grosser 38617f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 38717f01968SSiddharth Bhat GPURuntime Runtime; 38817f01968SSiddharth Bhat 38917f01968SSiddharth Bhat /// The GPU Architecture to target. 39017f01968SSiddharth Bhat GPUArch Arch; 39117f01968SSiddharth Bhat 392472f9654STobias Grosser /// Class to free isl_ids. 393472f9654STobias Grosser class IslIdDeleter { 394472f9654STobias Grosser public: 395472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 396472f9654STobias Grosser }; 397472f9654STobias Grosser 398472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 399472f9654STobias Grosser /// 400472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 401472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 402472f9654STobias Grosser 403edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 404edb885cbSTobias Grosser 40538fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 40638fc0aedSTobias Grosser /// 40738fc0aedSTobias Grosser /// These AST nodes can be of type: 40838fc0aedSTobias Grosser /// 40938fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 41038fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 41113c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 4125260c041STobias Grosser /// - In-kernel synchronization 4135260c041STobias Grosser /// - In-kernel memory copy statement 41438fc0aedSTobias Grosser /// 4151fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 4161fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 41732837fe3STobias Grosser 41813c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 41913c78e4dSTobias Grosser 42013c78e4dSTobias Grosser /// Create code for a data transfer statement 42113c78e4dSTobias Grosser /// 42213c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 42313c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 42413c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 42513c78e4dSTobias Grosser enum DataDirection Direction); 42613c78e4dSTobias Grosser 427edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 428edb885cbSTobias Grosser /// 429edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 430edb885cbSTobias Grosser /// 431e53c924bSSiddharth Bhat /// @returns A tuple, whose: 432e53c924bSSiddharth Bhat /// - First element contains the set of values referenced by the 433e53c924bSSiddharth Bhat /// kernel 434e53c924bSSiddharth Bhat /// - Second element contains the set of functions referenced by the 435e53c924bSSiddharth Bhat /// kernel. All functions in the set satisfy 436e53c924bSSiddharth Bhat /// `isValidFunctionInKernel`. 437e53c924bSSiddharth Bhat /// - Third element contains loops that have induction variables 438e53c924bSSiddharth Bhat /// which are used in the kernel, *and* these loops are *neither* 439e53c924bSSiddharth Bhat /// in the scop, nor do they immediately surroung the Scop. 440e53c924bSSiddharth Bhat /// See [Code generation of induction variables of loops outside 441e53c924bSSiddharth Bhat /// Scops] 44243df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 44343df2020STobias Grosser isl::space> 444f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 445edb885cbSTobias Grosser 44679a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 44779a947c2STobias Grosser /// 44879a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 44979a947c2STobias Grosser /// 45079a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 45179a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 45279a947c2STobias Grosser 453b99c1171STobias Grosser /// Get the managed array pointer for sending host pointers to the device. 454abed4969SSiddharth Bhat /// \note 455abed4969SSiddharth Bhat /// This is to be used only with managed memory 456b99c1171STobias Grosser Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo); 457abed4969SSiddharth Bhat 45879a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 45979a947c2STobias Grosser /// 46079a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 46179a947c2STobias Grosser /// 46279a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 46379a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 46479a947c2STobias Grosser 465a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 466a90be207SSiddharth Bhat /// parameters. 467a90be207SSiddharth Bhat /// 468a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 469a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 470a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 471a90be207SSiddharth Bhat /// parameter. 472a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 473a90be207SSiddharth Bhat int Index); 474a90be207SSiddharth Bhat 47579a947c2STobias Grosser /// Create kernel launch parameters. 47679a947c2STobias Grosser /// 47779a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 47879a947c2STobias Grosser /// @param F The kernel function that has been created. 47957693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 48079a947c2STobias Grosser /// 48179a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 48279a947c2STobias Grosser /// values that are passed to the kernel. 48357693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 48457693272STobias Grosser SetVector<Value *> SubtreeValues); 48579a947c2STobias Grosser 486b513b491STobias Grosser /// Create declarations for kernel variable. 487b513b491STobias Grosser /// 488b513b491STobias Grosser /// This includes shared memory declarations. 489b513b491STobias Grosser /// 490b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 491b513b491STobias Grosser /// @param FN The function into which to generate the variables. 492b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 493b513b491STobias Grosser 494c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 495c1c6a2a6STobias Grosser /// 496c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 497c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 498c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 499c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 500c1c6a2a6STobias Grosser /// as specified here. 501c1c6a2a6STobias Grosser /// 502c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 503c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 504c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 505c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 506c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 507c1c6a2a6STobias Grosser Value *BlockDimZ); 508c1c6a2a6STobias Grosser 50932837fe3STobias Grosser /// Create GPU kernel. 51032837fe3STobias Grosser /// 51132837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 51232837fe3STobias Grosser /// 51332837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 51432837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 51532837fe3STobias Grosser 51613c78e4dSTobias Grosser /// Generate code that computes the size of an array. 51713c78e4dSTobias Grosser /// 51813c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 51913c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 52013c78e4dSTobias Grosser 521aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 522aaabbbf8STobias Grosser /// 523aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 524aaabbbf8STobias Grosser /// 525aaabbbf8STobias Grosser /// Example: 526aaabbbf8STobias Grosser /// 527aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 528aaabbbf8STobias Grosser /// A[i + 42] += ... 529aaabbbf8STobias Grosser /// 530aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 531aaabbbf8STobias Grosser /// 532aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 533aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 534aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 535aaabbbf8STobias Grosser 53600bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 53700bb5a99STobias Grosser /// 53800bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 53900bb5a99STobias Grosser /// @param FN The function created for the kernel. 54000bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 54100bb5a99STobias Grosser 54232837fe3STobias Grosser /// Create kernel function. 54332837fe3STobias Grosser /// 54432837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 54532837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 54632837fe3STobias Grosser /// start block of this newly created function. 54732837fe3STobias Grosser /// 54832837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 549edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 550f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 551f291c8d5SSiddharth Bhat /// kernel. 552edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 553f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 554f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 55532837fe3STobias Grosser 55632837fe3STobias Grosser /// Create the declaration of a kernel function. 55732837fe3STobias Grosser /// 55832837fe3STobias Grosser /// The kernel function takes as arguments: 55932837fe3STobias Grosser /// 56032837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 561f6044bd0STobias Grosser /// - Host iterators 562c84a1995STobias Grosser /// - Parameters 56332837fe3STobias Grosser /// - Other LLVM Value references (TODO) 56432837fe3STobias Grosser /// 56532837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 566edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 567edb885cbSTobias Grosser /// 56832837fe3STobias Grosser /// @returns The newly declared function. 569edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 570edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 57132837fe3STobias Grosser 572472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 573472f9654STobias Grosser /// 574472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 575472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 576472f9654STobias Grosser 5772f3073b5SPhilipp Schaad /// Insert function calls to retrieve the SPIR group/local ids. 5782f3073b5SPhilipp Schaad /// 5792f3073b5SPhilipp Schaad /// @param The kernel to generate the function calls for. 5802f3073b5SPhilipp Schaad void insertKernelCallsSPIR(ppcg_kernel *Kernel); 5812f3073b5SPhilipp Schaad 582f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 583f291c8d5SSiddharth Bhat /// 584f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 585f291c8d5SSiddharth Bhat /// SubtreeFunctions. 586f291c8d5SSiddharth Bhat /// 587f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 588f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 589f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 590f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 591f291c8d5SSiddharth Bhat /// 592f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 593f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 594f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 595f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 596f291c8d5SSiddharth Bhat /// 597f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 598f291c8d5SSiddharth Bhat /// this kernel. 599f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 600f291c8d5SSiddharth Bhat 601b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 602b513b491STobias Grosser /// 603b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 604b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 605b513b491STobias Grosser 606edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 607edb885cbSTobias Grosser /// 608edb885cbSTobias Grosser /// @param Expr The expression containing the call. 609edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 610edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 611edb885cbSTobias Grosser 6125260c041STobias Grosser /// Create an in-kernel synchronization call. 6135260c041STobias Grosser void createKernelSync(); 6145260c041STobias Grosser 61574dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 61674dc3cb4STobias Grosser /// 61774dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 61874dc3cb4STobias Grosser std::string createKernelASM(); 61974dc3cb4STobias Grosser 62074dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 62174dc3cb4STobias Grosser /// 62274dc3cb4STobias Grosser /// @param F The function to remove references to. 62374dc3cb4STobias Grosser void clearDominators(Function *F); 62474dc3cb4STobias Grosser 62574dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 62674dc3cb4STobias Grosser /// 62774dc3cb4STobias Grosser /// @param F The function to remove references to. 62874dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 62974dc3cb4STobias Grosser 63074dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 63174dc3cb4STobias Grosser /// 63274dc3cb4STobias Grosser /// @param F The function to remove references to. 63374dc3cb4STobias Grosser void clearLoops(Function *F); 63474dc3cb4STobias Grosser 6358fc6cdfbSTobias Grosser /// Check if the scop requires to be linked with CUDA's libdevice. 6368fc6cdfbSTobias Grosser bool requiresCUDALibDevice(); 6378fc6cdfbSTobias Grosser 6388fc6cdfbSTobias Grosser /// Link with the NVIDIA libdevice library (if needed and available). 6398fc6cdfbSTobias Grosser void addCUDALibDevice(); 6408fc6cdfbSTobias Grosser 64132837fe3STobias Grosser /// Finalize the generation of the kernel function. 64232837fe3STobias Grosser /// 64332837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 64432837fe3STobias Grosser /// dump its IR to stderr. 64557793596STobias Grosser /// 64657793596STobias Grosser /// @returns The Assembly string of the kernel. 64757793596STobias Grosser std::string finalizeKernelFunction(); 648fa7b0802STobias Grosser 64951dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 65051dfc275STobias Grosser /// 65151dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 652a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 65351dfc275STobias Grosser /// the kernel terminates. 65451dfc275STobias Grosser /// 65551dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 65651dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 65751dfc275STobias Grosser 6587287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 659fa7b0802STobias Grosser void allocateDeviceArrays(); 660fa7b0802STobias Grosser 661b99c1171STobias Grosser /// Create code to prepare the managed device pointers. 662b99c1171STobias Grosser void prepareManagedDeviceArrays(); 663b99c1171STobias Grosser 6647287aeddSTobias Grosser /// Free all allocated device arrays. 6657287aeddSTobias Grosser void freeDeviceArrays(); 6667287aeddSTobias Grosser 667fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 668fa7b0802STobias Grosser /// 669fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 670fa7b0802STobias Grosser Value *createCallInitContext(); 671fa7b0802STobias Grosser 67279a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 67379a947c2STobias Grosser /// 67479a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 67579a947c2STobias Grosser /// 67679a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 67779a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 67879a947c2STobias Grosser 679fa7b0802STobias Grosser /// Create a call to free the GPU context. 680fa7b0802STobias Grosser /// 681fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 682fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 683fa7b0802STobias Grosser 6847287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6857287aeddSTobias Grosser /// 6867287aeddSTobias Grosser /// @param Size The size of memory to allocate 6877287aeddSTobias Grosser /// 6887287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 689fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6907287aeddSTobias Grosser 6917287aeddSTobias Grosser /// Create a call to free a device array. 6927287aeddSTobias Grosser /// 6937287aeddSTobias Grosser /// @param Array The device array to free. 6947287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 69513c78e4dSTobias Grosser 69613c78e4dSTobias Grosser /// Create a call to copy data from host to device. 69713c78e4dSTobias Grosser /// 69813c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 69913c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 70013c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 70113c78e4dSTobias Grosser Value *Size); 70213c78e4dSTobias Grosser 70313c78e4dSTobias Grosser /// Create a call to copy data from device to host. 70413c78e4dSTobias Grosser /// 70513c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 70613c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 70713c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 70813c78e4dSTobias Grosser Value *Size); 70957793596STobias Grosser 710abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 711abed4969SSiddharth Bhat /// \note 712abed4969SSiddharth Bhat /// This is to be used only with managed memory. 713abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 714abed4969SSiddharth Bhat 71557793596STobias Grosser /// Create a call to get a kernel from an assembly string. 71657793596STobias Grosser /// 71757793596STobias Grosser /// @param Buffer The string describing the kernel. 71857793596STobias Grosser /// @param Entry The name of the kernel function to call. 71957793596STobias Grosser /// 72057793596STobias Grosser /// @returns A pointer to a kernel object 72157793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 72257793596STobias Grosser 72357793596STobias Grosser /// Create a call to free a GPU kernel. 72457793596STobias Grosser /// 72557793596STobias Grosser /// @param GPUKernel THe kernel to free. 72657793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 72779a947c2STobias Grosser 72879a947c2STobias Grosser /// Create a call to launch a GPU kernel. 72979a947c2STobias Grosser /// 73079a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 73179a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 73279a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 73379a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 73479a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 73579a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 736a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 73779a947c2STobias Grosser /// the parameter values passed for each kernel argument. 73879a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 73979a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 74079a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 74179a947c2STobias Grosser Value *Parameters); 7421fb9b64dSTobias Grosser }; 7431fb9b64dSTobias Grosser 74479f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 7451abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 7461abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 74779f13b9aSSingapuram Sanjay Srivallabh } 74879f13b9aSSingapuram Sanjay Srivallabh 749fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 750750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 751750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 752750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 753750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 754750160e2STobias Grosser 755fa7b0802STobias Grosser GPUContext = createCallInitContext(); 756abed4969SSiddharth Bhat 757c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 758fa7b0802STobias Grosser allocateDeviceArrays(); 759b99c1171STobias Grosser else 760b99c1171STobias Grosser prepareManagedDeviceArrays(); 761fa7b0802STobias Grosser } 762fa7b0802STobias Grosser 763fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 764c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 7657287aeddSTobias Grosser freeDeviceArrays(); 766abed4969SSiddharth Bhat 767fa7b0802STobias Grosser createCallFreeContext(GPUContext); 768fa7b0802STobias Grosser IslNodeBuilder::finalize(); 769fa7b0802STobias Grosser } 770fa7b0802STobias Grosser 771fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 772c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 773c4a4af47SSiddharth Bhat "Managed memory will directly send host pointers " 774abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 7758ea1fc19STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release()); 776fa7b0802STobias Grosser 777fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 778fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 77913c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7807287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7817287aeddSTobias Grosser DevArrayName.append(Array->name); 782fa7b0802STobias Grosser 78313c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 784aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 785aaabbbf8STobias Grosser if (Offset) 786aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 787aaabbbf8STobias Grosser ArraySize, 788aaabbbf8STobias Grosser Builder.CreateMul(Offset, 789aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 79034eeabbcSSiddharth Bhat const SCEV *SizeSCEV = SE.getSCEV(ArraySize); 79134eeabbcSSiddharth Bhat // It makes no sense to have an array of size 0. The CUDA API will 79234eeabbcSSiddharth Bhat // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We 79334eeabbcSSiddharth Bhat // choose to be defensive and catch this at the compile phase. It is 79434eeabbcSSiddharth Bhat // most likely that we are doing something wrong with size computation. 79534eeabbcSSiddharth Bhat if (SizeSCEV->isZero()) { 79634eeabbcSSiddharth Bhat errs() << getUniqueScopName(&S) 79734eeabbcSSiddharth Bhat << " has computed array size 0: " << *ArraySize 79834eeabbcSSiddharth Bhat << " | for array: " << *(ScopArray->getBasePtr()) 79934eeabbcSSiddharth Bhat << ". This is illegal, exiting.\n"; 80034eeabbcSSiddharth Bhat report_fatal_error("array size was computed to be 0"); 80134eeabbcSSiddharth Bhat } 80234eeabbcSSiddharth Bhat 8037287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 8047287aeddSTobias Grosser DevArray->setName(DevArrayName); 80513c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 806fa7b0802STobias Grosser } 807fa7b0802STobias Grosser 808fa7b0802STobias Grosser isl_ast_build_free(Build); 809fa7b0802STobias Grosser } 810fa7b0802STobias Grosser 811b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() { 812c4a4af47SSiddharth Bhat assert(PollyManagedMemory && 813b99c1171STobias Grosser "Device array most only be prepared in managed-memory mode"); 814b99c1171STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 815b99c1171STobias Grosser gpu_array_info *Array = &Prog->array[i]; 816b99c1171STobias Grosser ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user; 817b99c1171STobias Grosser Value *HostPtr; 818b99c1171STobias Grosser 819b99c1171STobias Grosser if (gpu_array_is_scalar(Array)) 820b99c1171STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 821b99c1171STobias Grosser else 822b99c1171STobias Grosser HostPtr = ScopArray->getBasePtr(); 823b99c1171STobias Grosser HostPtr = getLatestValue(HostPtr); 824b99c1171STobias Grosser 825b99c1171STobias Grosser Value *Offset = getArrayOffset(Array); 826b99c1171STobias Grosser if (Offset) { 827b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast( 828b99c1171STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 829b99c1171STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 830b99c1171STobias Grosser } 831b99c1171STobias Grosser 832b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 833b99c1171STobias Grosser DeviceAllocations[ScopArray] = HostPtr; 834b99c1171STobias Grosser } 835b99c1171STobias Grosser } 836b99c1171STobias Grosser 837c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 838c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 839c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 840c1c6a2a6STobias Grosser 841c1c6a2a6STobias Grosser for (auto &F : *M) { 842c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 843c1c6a2a6STobias Grosser continue; 844c1c6a2a6STobias Grosser 845c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 846c1c6a2a6STobias Grosser 847c1c6a2a6STobias Grosser Metadata *Elements[] = { 848c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 849c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 850c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 851c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 852c1c6a2a6STobias Grosser }; 853c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 854c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 855c1c6a2a6STobias Grosser } 856c1c6a2a6STobias Grosser } 857c1c6a2a6STobias Grosser 8587287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 859c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory does not use device arrays"); 86013c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 86113c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 8627287aeddSTobias Grosser } 8637287aeddSTobias Grosser 86457793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 86557793596STobias Grosser const char *Name = "polly_getKernel"; 86657793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 86757793596STobias Grosser Function *F = M->getFunction(Name); 86857793596STobias Grosser 86957793596STobias Grosser // If F is not available, declare it. 87057793596STobias Grosser if (!F) { 87157793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 87257793596STobias Grosser std::vector<Type *> Args; 87357793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87457793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87557793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 87657793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 87757793596STobias Grosser } 87857793596STobias Grosser 87957793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 88057793596STobias Grosser } 88157793596STobias Grosser 88279a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 88379a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 88479a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 88579a947c2STobias Grosser Function *F = M->getFunction(Name); 88679a947c2STobias Grosser 88779a947c2STobias Grosser // If F is not available, declare it. 88879a947c2STobias Grosser if (!F) { 88979a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 89079a947c2STobias Grosser std::vector<Type *> Args; 89179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 89279a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 89379a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 89479a947c2STobias Grosser } 89579a947c2STobias Grosser 89679a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 89779a947c2STobias Grosser } 89879a947c2STobias Grosser 89979a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 90079a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 90179a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 90279a947c2STobias Grosser Value *Parameters) { 90379a947c2STobias Grosser const char *Name = "polly_launchKernel"; 90479a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 90579a947c2STobias Grosser Function *F = M->getFunction(Name); 90679a947c2STobias Grosser 90779a947c2STobias Grosser // If F is not available, declare it. 90879a947c2STobias Grosser if (!F) { 90979a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 91079a947c2STobias Grosser std::vector<Type *> Args; 91179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91279a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91379a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91479a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91579a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91779a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91879a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 91979a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 92079a947c2STobias Grosser } 92179a947c2STobias Grosser 922ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 92379a947c2STobias Grosser BlockDimZ, Parameters}); 92479a947c2STobias Grosser } 92579a947c2STobias Grosser 92657793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 92757793596STobias Grosser const char *Name = "polly_freeKernel"; 92857793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 92957793596STobias Grosser Function *F = M->getFunction(Name); 93057793596STobias Grosser 93157793596STobias Grosser // If F is not available, declare it. 93257793596STobias Grosser if (!F) { 93357793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 93457793596STobias Grosser std::vector<Type *> Args; 93557793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93657793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 93757793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 93857793596STobias Grosser } 93957793596STobias Grosser 94057793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 94157793596STobias Grosser } 94257793596STobias Grosser 9437287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 944c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 945c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 946abed4969SSiddharth Bhat "for device"); 9477287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 9487287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9497287aeddSTobias Grosser Function *F = M->getFunction(Name); 9507287aeddSTobias Grosser 9517287aeddSTobias Grosser // If F is not available, declare it. 9527287aeddSTobias Grosser if (!F) { 9537287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 9547287aeddSTobias Grosser std::vector<Type *> Args; 9557287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 9567287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 9577287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 9587287aeddSTobias Grosser } 9597287aeddSTobias Grosser 9607287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 9617287aeddSTobias Grosser } 9627287aeddSTobias Grosser 963fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 964c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 965c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 966abed4969SSiddharth Bhat "for device"); 967fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 968fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 969fa7b0802STobias Grosser Function *F = M->getFunction(Name); 970fa7b0802STobias Grosser 971fa7b0802STobias Grosser // If F is not available, declare it. 972fa7b0802STobias Grosser if (!F) { 973fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 974fa7b0802STobias Grosser std::vector<Type *> Args; 975fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 976fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 977fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 978fa7b0802STobias Grosser } 979fa7b0802STobias Grosser 980fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 981fa7b0802STobias Grosser } 982fa7b0802STobias Grosser 98313c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 98413c78e4dSTobias Grosser Value *DeviceData, 98513c78e4dSTobias Grosser Value *Size) { 986c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 987c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 988abed4969SSiddharth Bhat "device and host"); 98913c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 99013c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 99113c78e4dSTobias Grosser Function *F = M->getFunction(Name); 99213c78e4dSTobias Grosser 99313c78e4dSTobias Grosser // If F is not available, declare it. 99413c78e4dSTobias Grosser if (!F) { 99513c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 99613c78e4dSTobias Grosser std::vector<Type *> Args; 99713c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99813c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99913c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 100013c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 100113c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 100213c78e4dSTobias Grosser } 100313c78e4dSTobias Grosser 100413c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 100513c78e4dSTobias Grosser } 100613c78e4dSTobias Grosser 100713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 100813c78e4dSTobias Grosser Value *HostData, 100913c78e4dSTobias Grosser Value *Size) { 1010c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 1011c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 1012abed4969SSiddharth Bhat "device and host"); 101313c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 101413c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 101513c78e4dSTobias Grosser Function *F = M->getFunction(Name); 101613c78e4dSTobias Grosser 101713c78e4dSTobias Grosser // If F is not available, declare it. 101813c78e4dSTobias Grosser if (!F) { 101913c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 102013c78e4dSTobias Grosser std::vector<Type *> Args; 102113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 102213c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 102313c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 102413c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 102513c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 102613c78e4dSTobias Grosser } 102713c78e4dSTobias Grosser 102813c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 102913c78e4dSTobias Grosser } 103013c78e4dSTobias Grosser 1031abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 1032c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "explicit synchronization is only necessary for " 1033abed4969SSiddharth Bhat "managed memory"); 1034abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 1035abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1036abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 1037abed4969SSiddharth Bhat 1038abed4969SSiddharth Bhat // If F is not available, declare it. 1039abed4969SSiddharth Bhat if (!F) { 1040abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1041abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 1042abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 1043abed4969SSiddharth Bhat } 1044abed4969SSiddharth Bhat 1045abed4969SSiddharth Bhat Builder.CreateCall(F); 1046abed4969SSiddharth Bhat } 1047abed4969SSiddharth Bhat 1048fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 104917f01968SSiddharth Bhat const char *Name; 105017f01968SSiddharth Bhat 105117f01968SSiddharth Bhat switch (Runtime) { 105217f01968SSiddharth Bhat case GPURuntime::CUDA: 105317f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 105417f01968SSiddharth Bhat break; 105517f01968SSiddharth Bhat case GPURuntime::OpenCL: 105617f01968SSiddharth Bhat Name = "polly_initContextCL"; 105717f01968SSiddharth Bhat break; 105817f01968SSiddharth Bhat } 105917f01968SSiddharth Bhat 1060fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1061fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1062fa7b0802STobias Grosser 1063fa7b0802STobias Grosser // If F is not available, declare it. 1064fa7b0802STobias Grosser if (!F) { 1065fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1066fa7b0802STobias Grosser std::vector<Type *> Args; 1067fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1068fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1069fa7b0802STobias Grosser } 1070fa7b0802STobias Grosser 1071fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 1072fa7b0802STobias Grosser } 1073fa7b0802STobias Grosser 1074fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 1075fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 1076fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1077fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1078fa7b0802STobias Grosser 1079fa7b0802STobias Grosser // If F is not available, declare it. 1080fa7b0802STobias Grosser if (!F) { 1081fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1082fa7b0802STobias Grosser std::vector<Type *> Args; 1083fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 1084fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1085fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1086fa7b0802STobias Grosser } 1087fa7b0802STobias Grosser 1088fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 1089fa7b0802STobias Grosser } 1090fa7b0802STobias Grosser 10915260c041STobias Grosser /// Check if one string is a prefix of another. 10925260c041STobias Grosser /// 10935260c041STobias Grosser /// @param String The string in which to look for the prefix. 10945260c041STobias Grosser /// @param Prefix The prefix to look for. 10955260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 10965260c041STobias Grosser return String.find(Prefix) == 0; 10975260c041STobias Grosser } 10985260c041STobias Grosser 109913c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1100b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 110113c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 110213c78e4dSTobias Grosser 110313c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 1104f7face4bSSiddharth Bhat isl::multi_pw_aff ArrayBound = 1105f7face4bSSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Array->bound)); 1106f7face4bSSiddharth Bhat 1107f7face4bSSiddharth Bhat isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0); 1108f7face4bSSiddharth Bhat isl::ast_expr Res = Build.expr_from(OffsetDimZero); 110913c78e4dSTobias Grosser 111013c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 1111f7face4bSSiddharth Bhat isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i); 1112f7face4bSSiddharth Bhat isl::ast_expr Expr = Build.expr_from(Bound_I); 1113f7face4bSSiddharth Bhat Res = Res.mul(Expr); 111413c78e4dSTobias Grosser } 111513c78e4dSTobias Grosser 1116f7face4bSSiddharth Bhat Value *NumElements = ExprBuilder.create(Res.release()); 1117b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1118b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 111913c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 112013c78e4dSTobias Grosser } 112113c78e4dSTobias Grosser return ArraySize; 112213c78e4dSTobias Grosser } 112313c78e4dSTobias Grosser 1124aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1125aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1126aaabbbf8STobias Grosser return nullptr; 1127aaabbbf8STobias Grosser 1128b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1129aaabbbf8STobias Grosser 1130ccbf4b50SSiddharth Bhat isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin(); 1131aaabbbf8STobias Grosser 1132ccbf4b50SSiddharth Bhat isl::set ZeroSet = isl::set::universe(Min.get_space()); 1133aaabbbf8STobias Grosser 1134ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) 1135ccbf4b50SSiddharth Bhat ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1136aaabbbf8STobias Grosser 1137ccbf4b50SSiddharth Bhat if (Min.is_subset(ZeroSet)) { 1138aaabbbf8STobias Grosser return nullptr; 1139aaabbbf8STobias Grosser } 1140aaabbbf8STobias Grosser 1141ccbf4b50SSiddharth Bhat isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0)); 1142aaabbbf8STobias Grosser 1143ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) { 1144aaabbbf8STobias Grosser if (i > 0) { 1145ccbf4b50SSiddharth Bhat isl::pw_aff Bound_I = 1146ccbf4b50SSiddharth Bhat isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1147ccbf4b50SSiddharth Bhat isl::ast_expr BExpr = Build.expr_from(Bound_I); 1148ccbf4b50SSiddharth Bhat Result = Result.mul(BExpr); 1149aaabbbf8STobias Grosser } 1150ccbf4b50SSiddharth Bhat isl::pw_aff DimMin = Min.dim_min(i); 1151ccbf4b50SSiddharth Bhat isl::ast_expr MExpr = Build.expr_from(DimMin); 1152ccbf4b50SSiddharth Bhat Result = Result.add(MExpr); 1153aaabbbf8STobias Grosser } 1154aaabbbf8STobias Grosser 1155ccbf4b50SSiddharth Bhat return ExprBuilder.create(Result.release()); 1156aaabbbf8STobias Grosser } 1157aaabbbf8STobias Grosser 1158b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1159abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1160c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "Only used when you wish to get a host " 1161abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1162abed4969SSiddharth Bhat "with managed memory"); 1163abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1164b99c1171STobias Grosser it = DeviceAllocations.find(ArrayInfo); 1165b99c1171STobias Grosser assert(it != DeviceAllocations.end() && 1166b99c1171STobias Grosser "Device array expected to be available"); 1167abed4969SSiddharth Bhat return it->second; 1168abed4969SSiddharth Bhat } 1169abed4969SSiddharth Bhat 117013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 117113c78e4dSTobias Grosser enum DataDirection Direction) { 1172c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory needs no data transfers"); 117313c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 117413c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 117513c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 117613c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 117713c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 117813c78e4dSTobias Grosser 117913c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1180aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 118113c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 118213c78e4dSTobias Grosser 1183b06ff457STobias Grosser Value *HostPtr; 1184b06ff457STobias Grosser 1185b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1186b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1187b06ff457STobias Grosser else 1188b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 1189edf9581eSSiddharth Bhat HostPtr = getLatestValue(HostPtr); 119013c78e4dSTobias Grosser 1191aaabbbf8STobias Grosser if (Offset) { 1192aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1193aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1194aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1195aaabbbf8STobias Grosser } 1196aaabbbf8STobias Grosser 119713c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 119813c78e4dSTobias Grosser 1199aaabbbf8STobias Grosser if (Offset) { 1200aaabbbf8STobias Grosser Size = Builder.CreateSub( 1201ff40087aSTobias Grosser Size, Builder.CreateMul( 1202ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1203aaabbbf8STobias Grosser } 1204aaabbbf8STobias Grosser 120513c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 120613c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 120713c78e4dSTobias Grosser else 120813c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 120913c78e4dSTobias Grosser 121013c78e4dSTobias Grosser isl_id_free(Id); 121113c78e4dSTobias Grosser isl_ast_expr_free(Arg); 121213c78e4dSTobias Grosser isl_ast_expr_free(Expr); 121313c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 121413c78e4dSTobias Grosser } 121513c78e4dSTobias Grosser 12161fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 121732837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 121832837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 121932837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 122032837fe3STobias Grosser isl_id_free(Id); 122132837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 122232837fe3STobias Grosser 122332837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 122432837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 122532837fe3STobias Grosser createKernel(UserStmt); 122662acb344STobias Grosser if (PollyManagedMemory) 122762acb344STobias Grosser createCallSynchronizeDevice(); 122832837fe3STobias Grosser isl_ast_expr_free(Expr); 122932837fe3STobias Grosser return; 123032837fe3STobias Grosser } 12319e3db2b7SSiddharth Bhat if (!strcmp(Str, "init_device")) { 12329e3db2b7SSiddharth Bhat initializeAfterRTH(); 12339e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12349e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12359e3db2b7SSiddharth Bhat return; 12369e3db2b7SSiddharth Bhat } 12379e3db2b7SSiddharth Bhat if (!strcmp(Str, "clear_device")) { 12389e3db2b7SSiddharth Bhat finalize(); 12399e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12409e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12419e3db2b7SSiddharth Bhat return; 12429e3db2b7SSiddharth Bhat } 124313c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1244c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 124513c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1246abed4969SSiddharth Bhat else 1247abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1248abed4969SSiddharth Bhat 124932837fe3STobias Grosser isl_ast_expr_free(Expr); 125013c78e4dSTobias Grosser return; 125113c78e4dSTobias Grosser } 125213c78e4dSTobias Grosser 125313c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1254c4a4af47SSiddharth Bhat if (!PollyManagedMemory) { 125513c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1256abed4969SSiddharth Bhat } else { 1257abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1258abed4969SSiddharth Bhat } 125913c78e4dSTobias Grosser isl_ast_expr_free(Expr); 126038fc0aedSTobias Grosser return; 126138fc0aedSTobias Grosser } 126238fc0aedSTobias Grosser 12635260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 12645260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 12655260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 12665260c041STobias Grosser isl_id_free(Anno); 12675260c041STobias Grosser 12685260c041STobias Grosser switch (KernelStmt->type) { 12695260c041STobias Grosser case ppcg_kernel_domain: 1270edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 12715260c041STobias Grosser isl_ast_node_free(UserStmt); 12725260c041STobias Grosser return; 12735260c041STobias Grosser case ppcg_kernel_copy: 1274b513b491STobias Grosser createKernelCopy(KernelStmt); 12755260c041STobias Grosser isl_ast_expr_free(Expr); 12765260c041STobias Grosser isl_ast_node_free(UserStmt); 12775260c041STobias Grosser return; 12785260c041STobias Grosser case ppcg_kernel_sync: 12795260c041STobias Grosser createKernelSync(); 12805260c041STobias Grosser isl_ast_expr_free(Expr); 12815260c041STobias Grosser isl_ast_node_free(UserStmt); 12825260c041STobias Grosser return; 12835260c041STobias Grosser } 12845260c041STobias Grosser 12855260c041STobias Grosser isl_ast_expr_free(Expr); 12865260c041STobias Grosser isl_ast_node_free(UserStmt); 12875260c041STobias Grosser return; 12885260c041STobias Grosser } 1289b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1290b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1291b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1292b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1293b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1294b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1295b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1296b513b491STobias Grosser 1297b513b491STobias Grosser if (KernelStmt->u.c.read) { 1298b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1299b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1300b513b491STobias Grosser } else { 1301b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1302b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1303b513b491STobias Grosser } 1304b513b491STobias Grosser } 13055260c041STobias Grosser 1306edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1307edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1308edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1309edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1310edb885cbSTobias Grosser 1311edb885cbSTobias Grosser LoopToScevMapT LTS; 1312edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1313edb885cbSTobias Grosser 1314edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1315edb885cbSTobias Grosser 1316edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1317edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1318edb885cbSTobias Grosser else 1319a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1320edb885cbSTobias Grosser } 1321edb885cbSTobias Grosser 13225260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 13235260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13242f3073b5SPhilipp Schaad const char *SpirName = "__gen_ocl_barrier_global"; 132517f01968SSiddharth Bhat 132617f01968SSiddharth Bhat Function *Sync; 132717f01968SSiddharth Bhat 132817f01968SSiddharth Bhat switch (Arch) { 13292f3073b5SPhilipp Schaad case GPUArch::SPIR64: 13302f3073b5SPhilipp Schaad case GPUArch::SPIR32: 13312f3073b5SPhilipp Schaad Sync = M->getFunction(SpirName); 13322f3073b5SPhilipp Schaad 13332f3073b5SPhilipp Schaad // If Sync is not available, declare it. 13342f3073b5SPhilipp Schaad if (!Sync) { 13352f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 13362f3073b5SPhilipp Schaad std::vector<Type *> Args; 13372f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 13382f3073b5SPhilipp Schaad Sync = Function::Create(Ty, Linkage, SpirName, M); 13392f3073b5SPhilipp Schaad Sync->setCallingConv(CallingConv::SPIR_FUNC); 13402f3073b5SPhilipp Schaad } 13412f3073b5SPhilipp Schaad break; 134217f01968SSiddharth Bhat case GPUArch::NVPTX64: 134317f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 134417f01968SSiddharth Bhat break; 134517f01968SSiddharth Bhat } 134617f01968SSiddharth Bhat 13475260c041STobias Grosser Builder.CreateCall(Sync, {}); 13485260c041STobias Grosser } 13495260c041STobias Grosser 1350edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1351edb885cbSTobias Grosser /// 1352edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1353edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1354edb885cbSTobias Grosser /// 1355edb885cbSTobias Grosser /// @param Node The node to collect references for. 1356edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1357edb885cbSTobias Grosser /// 1358edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1359edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1360edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1361edb885cbSTobias Grosser return isl_bool_true; 1362edb885cbSTobias Grosser 1363edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1364edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1365edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1366edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1367edb885cbSTobias Grosser isl_id_free(Id); 1368edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1369edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1370edb885cbSTobias Grosser 1371edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1372edb885cbSTobias Grosser return isl_bool_true; 1373edb885cbSTobias Grosser 1374edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1375edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1376edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1377edb885cbSTobias Grosser isl_id_free(Id); 1378edb885cbSTobias Grosser 137900bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1380edb885cbSTobias Grosser 1381edb885cbSTobias Grosser return isl_bool_true; 1382edb885cbSTobias Grosser } 1383edb885cbSTobias Grosser 13848fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice. 13858fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = { 13865170b662STobias Grosser "exp", "expf", "expl", "cos", "cosf", "sqrt", 13875170b662STobias Grosser "sqrtf", "copysign", "copysignf", "copysignl", "log", "logf"}; 13888fc6cdfbSTobias Grosser 13898fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F. 13908fc6cdfbSTobias Grosser /// 13918fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA. 13928fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) { 13938fc6cdfbSTobias Grosser if (CUDALibDeviceFunctions.count(F->getName())) 13948fc6cdfbSTobias Grosser return std::string("__nv_") + std::string(F->getName()); 13958fc6cdfbSTobias Grosser 13968fc6cdfbSTobias Grosser return ""; 13978fc6cdfbSTobias Grosser } 13988fc6cdfbSTobias Grosser 1399f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 14008fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1401f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1402f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 140354491db6STobias Grosser // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 140454491db6STobias Grosser // "llvm.copysign". 140554491db6STobias Grosser const StringRef Name = F->getName(); 14068fc6cdfbSTobias Grosser 14078fc6cdfbSTobias Grosser if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0) 14088fc6cdfbSTobias Grosser return true; 14098fc6cdfbSTobias Grosser 141054491db6STobias Grosser return F->isIntrinsic() && 141154491db6STobias Grosser (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 1412b09bd74dSTobias Grosser Name.startswith("llvm.copysign") || Name.startswith("llvm.powi")); 1413f291c8d5SSiddharth Bhat } 1414f291c8d5SSiddharth Bhat 1415f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1416f291c8d5SSiddharth Bhat /// 1417f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1418f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1419f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1420f291c8d5SSiddharth Bhat /// `Function`s. 1421f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1422f291c8d5SSiddharth Bhat 1423f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1424f291c8d5SSiddharth Bhat static SetVector<Function *> 14258fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 14268fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 1427f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1428f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1429f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1430f291c8d5SSiddharth Bhat if (F) { 14318fc6cdfbSTobias Grosser assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 14328fc6cdfbSTobias Grosser "Code should have bailed out by " 1433f291c8d5SSiddharth Bhat "this point if an invalid function " 1434f291c8d5SSiddharth Bhat "were present in a kernel."); 1435f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1436f291c8d5SSiddharth Bhat } 1437f291c8d5SSiddharth Bhat } 1438f291c8d5SSiddharth Bhat return SubtreeFunctions; 1439f291c8d5SSiddharth Bhat } 1440f291c8d5SSiddharth Bhat 144143df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 144243df2020STobias Grosser isl::space> 1443f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1444edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1445edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1446edb885cbSTobias Grosser SetVector<const Loop *> Loops; 144743df2020STobias Grosser isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params(); 1448edb885cbSTobias Grosser SubtreeReferences References = { 144943df2020STobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(), 145043df2020STobias Grosser &ParamSpace}; 1451edb885cbSTobias Grosser 1452edb885cbSTobias Grosser for (const auto &I : IDToValue) 1453edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1454edb885cbSTobias Grosser 1455e53c924bSSiddharth Bhat // NOTE: this is populated in IslNodeBuilder::addParameters 1456e53c924bSSiddharth Bhat // See [Code generation of induction variables of loops outside Scops]. 1457e53c924bSSiddharth Bhat for (const auto &I : OutsideLoopIterations) 1458e53c924bSSiddharth Bhat SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1459e53c924bSSiddharth Bhat 1460edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1461edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1462edb885cbSTobias Grosser 1463e53c924bSSiddharth Bhat for (const SCEV *Expr : SCEVs) { 1464edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1465e53c924bSSiddharth Bhat findLoops(Expr, Loops); 1466e53c924bSSiddharth Bhat } 1467e53c924bSSiddharth Bhat 1468e53c924bSSiddharth Bhat Loops.remove_if([this](const Loop *L) { 1469e53c924bSSiddharth Bhat return S.contains(L) || L->contains(S.getEntry()); 1470e53c924bSSiddharth Bhat }); 1471edb885cbSTobias Grosser 1472edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1473d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1474edb885cbSTobias Grosser 1475b65ccc43STobias Grosser isl_space *Space = S.getParamSpace().release(); 1476edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1477edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1478edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1479edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1480edb885cbSTobias Grosser SubtreeValues.remove(Val); 1481edb885cbSTobias Grosser isl_id_free(Id); 1482edb885cbSTobias Grosser } 1483edb885cbSTobias Grosser isl_space_free(Space); 1484edb885cbSTobias Grosser 1485edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1486edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1487edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1488edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1489edb885cbSTobias Grosser SubtreeValues.remove(Val); 1490edb885cbSTobias Grosser isl_id_free(Id); 1491edb885cbSTobias Grosser } 1492edb885cbSTobias Grosser 1493f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1494f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1495f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1496f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1497f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1498f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1499f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1500f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1501f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 15028fc6cdfbSTobias Grosser 15038fc6cdfbSTobias Grosser bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 15048fc6cdfbSTobias Grosser 1505f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 15068fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1507f291c8d5SSiddharth Bhat 1508a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1509a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1510a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1511a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1512a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1513a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1514a1b2086aSSiddharth Bhat else 1515a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1516a1b2086aSSiddharth Bhat } 151743df2020STobias Grosser return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops, 151843df2020STobias Grosser ParamSpace); 1519edb885cbSTobias Grosser } 1520edb885cbSTobias Grosser 152174dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 152274dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 152374dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 152474dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 152574dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 152674dc3cb4STobias Grosser 152774dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 152874dc3cb4STobias Grosser DT.eraseNode(BB); 152974dc3cb4STobias Grosser } 153074dc3cb4STobias Grosser 153174dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 153274dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 153374dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 153474dc3cb4STobias Grosser if (L) 153574dc3cb4STobias Grosser SE.forgetLoop(L); 153674dc3cb4STobias Grosser } 153774dc3cb4STobias Grosser } 153874dc3cb4STobias Grosser 153974dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 154074dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 154174dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 154274dc3cb4STobias Grosser if (L) 154374dc3cb4STobias Grosser SE.forgetLoop(L); 154474dc3cb4STobias Grosser LI.removeBlock(&BB); 154574dc3cb4STobias Grosser } 154674dc3cb4STobias Grosser } 154774dc3cb4STobias Grosser 154879a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 154979a947c2STobias Grosser std::vector<Value *> Sizes; 15508ea1fc19STobias Grosser isl::ast_build Context = isl::ast_build::from_context(S.getContext()); 155179a947c2STobias Grosser 15524d5820d1SSiddharth Bhat isl::multi_pw_aff GridSizePwAffs = 15534d5820d1SSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size)); 155479a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 15554d5820d1SSiddharth Bhat isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i); 15564d5820d1SSiddharth Bhat isl::ast_expr GridSize = Context.expr_from(Size); 15574d5820d1SSiddharth Bhat Value *Res = ExprBuilder.create(GridSize.release()); 155879a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 155979a947c2STobias Grosser Sizes.push_back(Res); 156079a947c2STobias Grosser } 156179a947c2STobias Grosser 156279a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 156379a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 156479a947c2STobias Grosser 156579a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 156679a947c2STobias Grosser } 156779a947c2STobias Grosser 156879a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 156979a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 157079a947c2STobias Grosser std::vector<Value *> Sizes; 157179a947c2STobias Grosser 157279a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 157379a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 157479a947c2STobias Grosser Sizes.push_back(Res); 157579a947c2STobias Grosser } 157679a947c2STobias Grosser 157779a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 157879a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 157979a947c2STobias Grosser 158079a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 158179a947c2STobias Grosser } 158279a947c2STobias Grosser 1583a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1584a90be207SSiddharth Bhat Instruction *Param, int Index) { 1585a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1586a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1587a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1588a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1589a90be207SSiddharth Bhat } 1590a90be207SSiddharth Bhat 159157693272STobias Grosser Value * 159257693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 159357693272STobias Grosser SetVector<Value *> SubtreeValues) { 1594a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1595a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1596a90be207SSiddharth Bhat 159750139f0fSPhilipp Schaad // If we are using the OpenCL Runtime, we need to add the kernel argument 159850139f0fSPhilipp Schaad // sizes to the end of the launch-parameter list, so OpenCL can determine 159950139f0fSPhilipp Schaad // how big the respective kernel arguments are. 160050139f0fSPhilipp Schaad // Here we need to reserve adequate space for that. 160150139f0fSPhilipp Schaad Type *ArrayTy; 160250139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 160350139f0fSPhilipp Schaad ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 160450139f0fSPhilipp Schaad else 160550139f0fSPhilipp Schaad ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs); 160679a947c2STobias Grosser 160779a947c2STobias Grosser BasicBlock *EntryBlock = 160879a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 160967726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 161079a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 161167726b32STobias Grosser Instruction *Parameters = new AllocaInst( 161267726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 161379a947c2STobias Grosser 161479a947c2STobias Grosser int Index = 0; 161579a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 161679a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 161779a947c2STobias Grosser continue; 161879a947c2STobias Grosser 161979a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1620206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 162179a947c2STobias Grosser 162250139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1623a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1624a90be207SSiddharth Bhat 1625abed4969SSiddharth Bhat Value *DevArray = nullptr; 1626c4a4af47SSiddharth Bhat if (PollyManagedMemory) { 1627b99c1171STobias Grosser DevArray = getManagedDeviceArray(&Prog->array[i], 1628b99c1171STobias Grosser const_cast<ScopArrayInfo *>(SAI)); 1629abed4969SSiddharth Bhat } else { 1630abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 163179a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1632abed4969SSiddharth Bhat } 1633abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1634abed4969SSiddharth Bhat "initialized"); 1635aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1636aaabbbf8STobias Grosser 1637aaabbbf8STobias Grosser if (Offset) { 1638aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1639aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1640aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1641aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1642aaabbbf8STobias Grosser } 1643fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1644fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1645aaabbbf8STobias Grosser 1646fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1647abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1648c4a4af47SSiddharth Bhat if (PollyManagedMemory) 1649abed4969SSiddharth Bhat ValPtr = DevArray; 1650abed4969SSiddharth Bhat else 1651abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1652abed4969SSiddharth Bhat 1653abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1654abed4969SSiddharth Bhat " to be stored into Parameters"); 1655fe74a7a1STobias Grosser Value *ValPtrCast = 1656fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1657fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1658fe74a7a1STobias Grosser } else { 165967726b32STobias Grosser Instruction *Param = 166067726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 166167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 166279a947c2STobias Grosser EntryBlock->getTerminator()); 166379a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 166479a947c2STobias Grosser Value *ParamTyped = 166579a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 166679a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1667fe74a7a1STobias Grosser } 166879a947c2STobias Grosser Index++; 166979a947c2STobias Grosser } 167079a947c2STobias Grosser 1671a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1672a490147cSTobias Grosser 1673a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1674a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1675a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1676a490147cSTobias Grosser isl_id_free(Id); 1677a90be207SSiddharth Bhat 167850139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1679a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1680a90be207SSiddharth Bhat 168167726b32STobias Grosser Instruction *Param = 168267726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 168367726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1684a490147cSTobias Grosser EntryBlock->getTerminator()); 1685a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1686a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1687a490147cSTobias Grosser Index++; 1688a490147cSTobias Grosser } 1689a490147cSTobias Grosser 1690d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1691d8b94bcaSTobias Grosser 1692d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1693d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1694d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1695a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1696a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1697d8b94bcaSTobias Grosser isl_id_free(Id); 1698a90be207SSiddharth Bhat 169950139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1700a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1701a90be207SSiddharth Bhat 170267726b32STobias Grosser Instruction *Param = 170367726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 170467726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1705d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1706d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1707a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1708d8b94bcaSTobias Grosser Index++; 1709d8b94bcaSTobias Grosser } 1710d8b94bcaSTobias Grosser 171157693272STobias Grosser for (auto Val : SubtreeValues) { 171250139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) 1713a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1714a90be207SSiddharth Bhat 171567726b32STobias Grosser Instruction *Param = 171667726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 171767726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 171857693272STobias Grosser EntryBlock->getTerminator()); 171957693272STobias Grosser Builder.CreateStore(Val, Param); 1720a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1721a90be207SSiddharth Bhat Index++; 1722a90be207SSiddharth Bhat } 1723a90be207SSiddharth Bhat 172450139f0fSPhilipp Schaad if (Runtime == GPURuntime::OpenCL) { 1725a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1726a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1727a90be207SSiddharth Bhat Instruction *Param = 1728a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1729a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1730a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1731a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1732a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 173357693272STobias Grosser Index++; 173457693272STobias Grosser } 173550139f0fSPhilipp Schaad } 173657693272STobias Grosser 173779a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 173879a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 173979a947c2STobias Grosser Launch + "_params_i8ptr", Location); 174079a947c2STobias Grosser } 174179a947c2STobias Grosser 1742f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1743f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1744f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1745f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1746f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1747f291c8d5SSiddharth Bhat if (!Clone) 1748f291c8d5SSiddharth Bhat Clone = 1749f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1750f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1751f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1752f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1753f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1754f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1755f291c8d5SSiddharth Bhat } 1756f291c8d5SSiddharth Bhat } 175732837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 175832837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 175932837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 176032837fe3STobias Grosser isl_id_free(Id); 176132837fe3STobias Grosser isl_ast_node_free(KernelStmt); 176232837fe3STobias Grosser 1763bc653f20STobias Grosser if (Kernel->n_grid > 1) 1764bc653f20STobias Grosser DeepestParallel = 1765bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1766bc653f20STobias Grosser else 1767bc653f20STobias Grosser DeepestSequential = 1768bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1769bc653f20STobias Grosser 1770c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1771c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1772c1c6a2a6STobias Grosser 1773f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1774f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1775e53c924bSSiddharth Bhat SetVector<const Loop *> Loops; 177643df2020STobias Grosser isl::space ParamSpace; 177743df2020STobias Grosser std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) = 1778e53c924bSSiddharth Bhat getReferencesInKernel(Kernel); 1779edb885cbSTobias Grosser 178043df2020STobias Grosser // Add parameters that appear only in the access function to the kernel 178143df2020STobias Grosser // space. This is important to make sure that all isl_ids are passed as 178243df2020STobias Grosser // parameters to the kernel, even though we may not have all parameters 178343df2020STobias Grosser // in the context to improve compile time. 178443df2020STobias Grosser Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release()); 178543df2020STobias Grosser 178632837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 178732837fe3STobias Grosser 178832837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1789472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1790edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1791587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1792b06ff457STobias Grosser ScalarMap.clear(); 179332837fe3STobias Grosser 1794edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1795edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1796edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1797edb885cbSTobias Grosser for (const Loop *L : Loops) { 1798edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1799edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1800edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1801edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1802edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1803edb885cbSTobias Grosser SubtreeValues.insert(V); 1804edb885cbSTobias Grosser } 1805edb885cbSTobias Grosser 1806f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1807f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 180832837fe3STobias Grosser 180959ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 181059ab0705STobias Grosser 181151dfc275STobias Grosser finalizeKernelArguments(Kernel); 181274dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 18132f3073b5SPhilipp Schaad if (Arch == GPUArch::NVPTX64) 1814c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 181574dc3cb4STobias Grosser clearDominators(F); 181674dc3cb4STobias Grosser clearScalarEvolution(F); 181774dc3cb4STobias Grosser clearLoops(F); 181874dc3cb4STobias Grosser 1819472f9654STobias Grosser IDToValue = HostIDs; 182032837fe3STobias Grosser 1821b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1822b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1823edb885cbSTobias Grosser EscapeMap.clear(); 1824edb885cbSTobias Grosser IDToSAI.clear(); 182574dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 182674dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 18274d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 182874dc3cb4STobias Grosser LocalArrays.clear(); 1829edb885cbSTobias Grosser 183051dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 183151dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 183257693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 183379a947c2STobias Grosser 183479f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 183557793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 183657793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 183757793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 183879a947c2STobias Grosser 183979a947c2STobias Grosser Value *GridDimX, *GridDimY; 184079a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 184179a947c2STobias Grosser 184279a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 184379a947c2STobias Grosser BlockDimZ, Parameters); 184457793596STobias Grosser createCallFreeKernel(GPUKernel); 1845b513b491STobias Grosser 1846b513b491STobias Grosser for (auto Id : KernelIds) 1847b513b491STobias Grosser isl_id_free(Id); 1848b513b491STobias Grosser 1849b513b491STobias Grosser KernelIds.clear(); 185032837fe3STobias Grosser } 185132837fe3STobias Grosser 185232837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 185332837fe3STobias Grosser /// 185432837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 185532837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1856d277fedaSSiddharth Bhat std::string Ret = ""; 185732837fe3STobias Grosser 1858d277fedaSSiddharth Bhat if (!is64Bit) { 1859d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 186030caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1861d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1862d277fedaSSiddharth Bhat } else { 1863d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 186430caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1865d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1866d277fedaSSiddharth Bhat } 186732837fe3STobias Grosser 186832837fe3STobias Grosser return Ret; 186932837fe3STobias Grosser } 187032837fe3STobias Grosser 18712f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel. 18722f3073b5SPhilipp Schaad /// 18732f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture? 18742f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) { 18752f3073b5SPhilipp Schaad std::string Ret = ""; 18762f3073b5SPhilipp Schaad 18772f3073b5SPhilipp Schaad if (!is64Bit) { 18782f3073b5SPhilipp Schaad Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 187930caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 18802f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18812f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18822f3073b5SPhilipp Schaad } else { 18832f3073b5SPhilipp Schaad Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 188430caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 18852f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18862f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18872f3073b5SPhilipp Schaad } 18882f3073b5SPhilipp Schaad 18892f3073b5SPhilipp Schaad return Ret; 18902f3073b5SPhilipp Schaad } 18912f3073b5SPhilipp Schaad 1892edb885cbSTobias Grosser Function * 1893edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1894edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 189532837fe3STobias Grosser std::vector<Type *> Args; 189679f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 189732837fe3STobias Grosser 18982f3073b5SPhilipp Schaad std::vector<Metadata *> MemoryType; 18992f3073b5SPhilipp Schaad 190032837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 190132837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 190232837fe3STobias Grosser continue; 190332837fe3STobias Grosser 1904fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1905fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1906206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1907fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 19082f3073b5SPhilipp Schaad MemoryType.push_back( 19092f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1910fe74a7a1STobias Grosser } else { 1911d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1912d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 19132f3073b5SPhilipp Schaad MemoryType.push_back( 19142f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 191532837fe3STobias Grosser } 1916fe74a7a1STobias Grosser } 191732837fe3STobias Grosser 1918f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1919f6044bd0STobias Grosser 19202f3073b5SPhilipp Schaad for (long i = 0; i < NumHostIters; i++) { 1921f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 19222f3073b5SPhilipp Schaad MemoryType.push_back( 19232f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19242f3073b5SPhilipp Schaad } 1925f6044bd0STobias Grosser 1926c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1927c84a1995STobias Grosser 1928cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1929cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1930cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1931cf66ef26STobias Grosser isl_id_free(Id); 1932cf66ef26STobias Grosser Args.push_back(Val->getType()); 19332f3073b5SPhilipp Schaad MemoryType.push_back( 19342f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1935cf66ef26STobias Grosser } 1936c84a1995STobias Grosser 19372f3073b5SPhilipp Schaad for (auto *V : SubtreeValues) { 1938edb885cbSTobias Grosser Args.push_back(V->getType()); 19392f3073b5SPhilipp Schaad MemoryType.push_back( 19402f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19412f3073b5SPhilipp Schaad } 1942edb885cbSTobias Grosser 194332837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 194432837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 194532837fe3STobias Grosser GPUModule.get()); 194617f01968SSiddharth Bhat 19472f3073b5SPhilipp Schaad std::vector<Metadata *> EmptyStrings; 19482f3073b5SPhilipp Schaad 19492f3073b5SPhilipp Schaad for (unsigned int i = 0; i < MemoryType.size(); i++) { 19502f3073b5SPhilipp Schaad EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 19512f3073b5SPhilipp Schaad } 19522f3073b5SPhilipp Schaad 19532f3073b5SPhilipp Schaad if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 19542f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_addr_space", 19552f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), MemoryType)); 19562f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_name", 19572f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19582f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_access_qual", 19592f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19602f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type", 19612f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19622f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type_qual", 19632f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19642f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_base_type", 19652f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19662f3073b5SPhilipp Schaad } 19672f3073b5SPhilipp Schaad 196817f01968SSiddharth Bhat switch (Arch) { 196917f01968SSiddharth Bhat case GPUArch::NVPTX64: 197032837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 197117f01968SSiddharth Bhat break; 19722f3073b5SPhilipp Schaad case GPUArch::SPIR32: 19732f3073b5SPhilipp Schaad case GPUArch::SPIR64: 19742f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_KERNEL); 19752f3073b5SPhilipp Schaad break; 197617f01968SSiddharth Bhat } 197732837fe3STobias Grosser 197832837fe3STobias Grosser auto Arg = FN->arg_begin(); 197932837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 198032837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 198132837fe3STobias Grosser continue; 198232837fe3STobias Grosser 1983edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1984edb885cbSTobias Grosser 1985edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1986206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 1987206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 1988edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1989edb885cbSTobias Grosser Value *Val = &*Arg; 1990edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1991edb885cbSTobias Grosser isl_ast_build *Build = 1992edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1993f5aff704SRoman Gareev Sizes.push_back(nullptr); 1994edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1995edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 19969e3db2b7SSiddharth Bhat Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1997edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1998edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1999edb885cbSTobias Grosser } 2000edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 20014d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 200274dc3cb4STobias Grosser LocalArrays.push_back(Val); 2003edb885cbSTobias Grosser 2004edb885cbSTobias Grosser isl_ast_build_free(Build); 2005b513b491STobias Grosser KernelIds.push_back(Id); 2006edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 200732837fe3STobias Grosser Arg++; 200832837fe3STobias Grosser } 200932837fe3STobias Grosser 2010f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 2011f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 2012f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 2013f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 2014f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2015f6044bd0STobias Grosser Arg++; 2016f6044bd0STobias Grosser } 2017f6044bd0STobias Grosser 2018c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 2019c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 2020c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 202112453403STobias Grosser Value *Val = IDToValue[Id]; 202212453403STobias Grosser ValueMap[Val] = &*Arg; 2023c84a1995STobias Grosser IDToValue[Id] = &*Arg; 2024c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2025c84a1995STobias Grosser Arg++; 2026c84a1995STobias Grosser } 2027c84a1995STobias Grosser 2028edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 2029edb885cbSTobias Grosser Arg->setName(V->getName()); 2030edb885cbSTobias Grosser ValueMap[V] = &*Arg; 2031edb885cbSTobias Grosser Arg++; 2032edb885cbSTobias Grosser } 2033edb885cbSTobias Grosser 203432837fe3STobias Grosser return FN; 203532837fe3STobias Grosser } 203632837fe3STobias Grosser 2037472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 203817f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 203917f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 2040472f9654STobias Grosser 204117f01968SSiddharth Bhat switch (Arch) { 20422f3073b5SPhilipp Schaad case GPUArch::SPIR64: 20432f3073b5SPhilipp Schaad case GPUArch::SPIR32: 20442f3073b5SPhilipp Schaad llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 204517f01968SSiddharth Bhat case GPUArch::NVPTX64: 204617f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 204717f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 204817f01968SSiddharth Bhat 204917f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 205017f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 205117f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 205217f01968SSiddharth Bhat break; 205317f01968SSiddharth Bhat } 2054472f9654STobias Grosser 2055472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2056472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 2057472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2058472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2059472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2060472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2061472f9654STobias Grosser IDToValue[Id] = Val; 2062472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2063472f9654STobias Grosser }; 2064472f9654STobias Grosser 2065472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 2066472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2067472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 2068472f9654STobias Grosser } 2069472f9654STobias Grosser 2070472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 2071472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2072472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 2073472f9654STobias Grosser } 2074472f9654STobias Grosser } 2075472f9654STobias Grosser 20762f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 20772f3073b5SPhilipp Schaad const char *GroupName[3] = {"__gen_ocl_get_group_id0", 20782f3073b5SPhilipp Schaad "__gen_ocl_get_group_id1", 20792f3073b5SPhilipp Schaad "__gen_ocl_get_group_id2"}; 20802f3073b5SPhilipp Schaad 20812f3073b5SPhilipp Schaad const char *LocalName[3] = {"__gen_ocl_get_local_id0", 20822f3073b5SPhilipp Schaad "__gen_ocl_get_local_id1", 20832f3073b5SPhilipp Schaad "__gen_ocl_get_local_id2"}; 20842f3073b5SPhilipp Schaad 20852f3073b5SPhilipp Schaad auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 20862f3073b5SPhilipp Schaad Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 20872f3073b5SPhilipp Schaad Function *FN = M->getFunction(Name); 20882f3073b5SPhilipp Schaad 20892f3073b5SPhilipp Schaad // If FN is not available, declare it. 20902f3073b5SPhilipp Schaad if (!FN) { 20912f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 20922f3073b5SPhilipp Schaad std::vector<Type *> Args; 20932f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 20942f3073b5SPhilipp Schaad FN = Function::Create(Ty, Linkage, Name, M); 20952f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_FUNC); 20962f3073b5SPhilipp Schaad } 20972f3073b5SPhilipp Schaad 20982f3073b5SPhilipp Schaad Value *Val = Builder.CreateCall(FN, {}); 20992f3073b5SPhilipp Schaad Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 21002f3073b5SPhilipp Schaad IDToValue[Id] = Val; 21012f3073b5SPhilipp Schaad KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 21022f3073b5SPhilipp Schaad }; 21032f3073b5SPhilipp Schaad 21042f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_grid; ++i) 21052f3073b5SPhilipp Schaad createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 21062f3073b5SPhilipp Schaad 21072f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_block; ++i) 21082f3073b5SPhilipp Schaad createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 21092f3073b5SPhilipp Schaad } 21102f3073b5SPhilipp Schaad 211100bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 211200bb5a99STobias Grosser auto Arg = FN->arg_begin(); 211300bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 211400bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 211500bb5a99STobias Grosser continue; 211600bb5a99STobias Grosser 211700bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2118206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2119206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 212000bb5a99STobias Grosser isl_id_free(Id); 212100bb5a99STobias Grosser 212200bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 212300bb5a99STobias Grosser Arg++; 212400bb5a99STobias Grosser continue; 212500bb5a99STobias Grosser } 212600bb5a99STobias Grosser 2127fe74a7a1STobias Grosser Value *Val = &*Arg; 2128fe74a7a1STobias Grosser 2129fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 213000bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 2131fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2132fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 2133fe74a7a1STobias Grosser } 2134fe74a7a1STobias Grosser 2135fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 213600bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 213700bb5a99STobias Grosser 213800bb5a99STobias Grosser Arg++; 213900bb5a99STobias Grosser } 214000bb5a99STobias Grosser } 214100bb5a99STobias Grosser 214251dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 214351dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 214451dfc275STobias Grosser auto Arg = FN->arg_begin(); 214551dfc275STobias Grosser 214651dfc275STobias Grosser bool StoredScalar = false; 214751dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 214851dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 214951dfc275STobias Grosser continue; 215051dfc275STobias Grosser 215151dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2152206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2153206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 215451dfc275STobias Grosser isl_id_free(Id); 215551dfc275STobias Grosser 215651dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 215751dfc275STobias Grosser Arg++; 215851dfc275STobias Grosser continue; 215951dfc275STobias Grosser } 216051dfc275STobias Grosser 216151dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 216251dfc275STobias Grosser Arg++; 216351dfc275STobias Grosser continue; 216451dfc275STobias Grosser } 216551dfc275STobias Grosser 216651dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 216751dfc275STobias Grosser Value *ArgPtr = &*Arg; 216851dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 216951dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 217051dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 217151dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 217251dfc275STobias Grosser StoredScalar = true; 217351dfc275STobias Grosser 217451dfc275STobias Grosser Arg++; 217551dfc275STobias Grosser } 217651dfc275STobias Grosser 2177638316daSSiddharth Bhat if (StoredScalar) { 217851dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 217951dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 218051dfc275STobias Grosser /// To support this case we need to store these scalars back at each 218151dfc275STobias Grosser /// memory store or at least before each kernel barrier. 2182638316daSSiddharth Bhat if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 218351dfc275STobias Grosser BuildSuccessful = 0; 2184638316daSSiddharth Bhat DEBUG( 2185638316daSSiddharth Bhat dbgs() << getUniqueScopName(&S) 2186638316daSSiddharth Bhat << " has a store to a scalar value that" 2187638316daSSiddharth Bhat " would be undefined to run in parallel. Bailing out.\n";); 2188638316daSSiddharth Bhat } 2189638316daSSiddharth Bhat } 219051dfc275STobias Grosser } 219151dfc275STobias Grosser 2192b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2193b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2194b513b491STobias Grosser 2195b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 2196b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 2197b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2198206e9e3bSTobias Grosser Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2199b513b491STobias Grosser 2200f919d8b3STobias Grosser Type *ArrayTy = EleTy; 2201b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 2202b513b491STobias Grosser 2203f5aff704SRoman Gareev Sizes.push_back(nullptr); 2204928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2205b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2206f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 2207b513b491STobias Grosser isl_val_free(Val); 2208b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2209928d7573STobias Grosser } 2210928d7573STobias Grosser 2211928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 2212928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2213928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 2214928d7573STobias Grosser isl_val_free(Val); 2215b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 2216b513b491STobias Grosser } 2217b513b491STobias Grosser 2218130ca30fSTobias Grosser const ScopArrayInfo *SAI; 2219130ca30fSTobias Grosser Value *Allocation; 2220130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 2221130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 2222130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2223130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2224130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2225f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2226f919d8b3STobias Grosser 2227130ca30fSTobias Grosser Allocation = GlobalVar; 2228130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 2229130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2230130ca30fSTobias Grosser } else { 2231130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 2232130ca30fSTobias Grosser } 22334d5a9172STobias Grosser SAI = 22344d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2235b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2236130ca30fSTobias Grosser IDToValue[Id] = Allocation; 2237130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 2238b513b491STobias Grosser KernelIds.push_back(Id); 2239b513b491STobias Grosser IDToSAI[Id] = SAI; 2240b513b491STobias Grosser } 2241b513b491STobias Grosser } 2242b513b491STobias Grosser 2243f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 2244f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2245f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 224679f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 224732837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 224817f01968SSiddharth Bhat 224917f01968SSiddharth Bhat switch (Arch) { 225017f01968SSiddharth Bhat case GPUArch::NVPTX64: 225117f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 225232837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 225317f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 225417f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 225532837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 225617f01968SSiddharth Bhat break; 22572f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22582f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 22592f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 22602f3073b5SPhilipp Schaad break; 22612f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22622f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 22632f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 22642f3073b5SPhilipp Schaad break; 226517f01968SSiddharth Bhat } 226632837fe3STobias Grosser 2267edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 226832837fe3STobias Grosser 226959ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 227032837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 227132837fe3STobias Grosser 227259ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 227359ab0705STobias Grosser 227432837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 227532837fe3STobias Grosser Builder.CreateRetVoid(); 227632837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2277472f9654STobias Grosser 2278629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 2279629109b6STobias Grosser 228000bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2281b513b491STobias Grosser createKernelVariables(Kernel, FN); 22822f3073b5SPhilipp Schaad 22832f3073b5SPhilipp Schaad switch (Arch) { 22842f3073b5SPhilipp Schaad case GPUArch::NVPTX64: 2285472f9654STobias Grosser insertKernelIntrinsics(Kernel); 22862f3073b5SPhilipp Schaad break; 22872f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22882f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22892f3073b5SPhilipp Schaad insertKernelCallsSPIR(Kernel); 22902f3073b5SPhilipp Schaad break; 22912f3073b5SPhilipp Schaad } 229232837fe3STobias Grosser } 229332837fe3STobias Grosser 229474dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 229517f01968SSiddharth Bhat llvm::Triple GPUTriple; 229617f01968SSiddharth Bhat 229717f01968SSiddharth Bhat switch (Arch) { 229817f01968SSiddharth Bhat case GPUArch::NVPTX64: 229917f01968SSiddharth Bhat switch (Runtime) { 230017f01968SSiddharth Bhat case GPURuntime::CUDA: 230117f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 230217f01968SSiddharth Bhat break; 230317f01968SSiddharth Bhat case GPURuntime::OpenCL: 230417f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 230517f01968SSiddharth Bhat break; 230617f01968SSiddharth Bhat } 230717f01968SSiddharth Bhat break; 23082f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23092f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23102f3073b5SPhilipp Schaad std::string SPIRAssembly; 23112f3073b5SPhilipp Schaad raw_string_ostream IROstream(SPIRAssembly); 23122f3073b5SPhilipp Schaad IROstream << *GPUModule; 23132f3073b5SPhilipp Schaad IROstream.flush(); 23142f3073b5SPhilipp Schaad return SPIRAssembly; 231517f01968SSiddharth Bhat } 231617f01968SSiddharth Bhat 231774dc3cb4STobias Grosser std::string ErrMsg; 231874dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 231974dc3cb4STobias Grosser 232074dc3cb4STobias Grosser if (!GPUTarget) { 232174dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 232274dc3cb4STobias Grosser return ""; 232374dc3cb4STobias Grosser } 232474dc3cb4STobias Grosser 232574dc3cb4STobias Grosser TargetOptions Options; 232674dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 232717f01968SSiddharth Bhat 232817f01968SSiddharth Bhat std::string subtarget; 232917f01968SSiddharth Bhat 233017f01968SSiddharth Bhat switch (Arch) { 233117f01968SSiddharth Bhat case GPUArch::NVPTX64: 233217f01968SSiddharth Bhat subtarget = CudaVersion; 233317f01968SSiddharth Bhat break; 23342f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23352f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23362f3073b5SPhilipp Schaad llvm_unreachable("No subtarget for SPIR architecture"); 233717f01968SSiddharth Bhat } 233817f01968SSiddharth Bhat 233917f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 234017f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 234174dc3cb4STobias Grosser 234274dc3cb4STobias Grosser SmallString<0> ASMString; 234374dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 234474dc3cb4STobias Grosser llvm::legacy::PassManager PM; 234574dc3cb4STobias Grosser 234674dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 234774dc3cb4STobias Grosser 234874dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 234974dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 235074dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 235174dc3cb4STobias Grosser return ""; 235274dc3cb4STobias Grosser } 235374dc3cb4STobias Grosser 235474dc3cb4STobias Grosser PM.run(*GPUModule); 235574dc3cb4STobias Grosser 235674dc3cb4STobias Grosser return ASMStream.str(); 235774dc3cb4STobias Grosser } 235874dc3cb4STobias Grosser 23598fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() { 23605b307cdbSTobias Grosser bool RequiresLibDevice = false; 23618fc6cdfbSTobias Grosser for (Function &F : GPUModule->functions()) { 23628fc6cdfbSTobias Grosser if (!F.isDeclaration()) 23638fc6cdfbSTobias Grosser continue; 23648fc6cdfbSTobias Grosser 23658fc6cdfbSTobias Grosser std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F); 23668fc6cdfbSTobias Grosser if (CUDALibDeviceFunc.length() != 0) { 23678fc6cdfbSTobias Grosser F.setName(CUDALibDeviceFunc); 23685b307cdbSTobias Grosser RequiresLibDevice = true; 23698fc6cdfbSTobias Grosser } 23708fc6cdfbSTobias Grosser } 23718fc6cdfbSTobias Grosser 23725b307cdbSTobias Grosser return RequiresLibDevice; 23738fc6cdfbSTobias Grosser } 23748fc6cdfbSTobias Grosser 23758fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() { 23768fc6cdfbSTobias Grosser if (Arch != GPUArch::NVPTX64) 23778fc6cdfbSTobias Grosser return; 23788fc6cdfbSTobias Grosser 23798fc6cdfbSTobias Grosser if (requiresCUDALibDevice()) { 23808fc6cdfbSTobias Grosser SMDiagnostic Error; 23818fc6cdfbSTobias Grosser 23828fc6cdfbSTobias Grosser errs() << CUDALibDevice << "\n"; 23838fc6cdfbSTobias Grosser auto LibDeviceModule = 23848fc6cdfbSTobias Grosser parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 23858fc6cdfbSTobias Grosser 23868fc6cdfbSTobias Grosser if (!LibDeviceModule) { 23878fc6cdfbSTobias Grosser BuildSuccessful = false; 23888fc6cdfbSTobias Grosser report_fatal_error("Could not find or load libdevice. Skipping GPU " 23898fc6cdfbSTobias Grosser "kernel generation. Please set -polly-acc-libdevice " 23908fc6cdfbSTobias Grosser "accordingly.\n"); 23918fc6cdfbSTobias Grosser return; 23928fc6cdfbSTobias Grosser } 23938fc6cdfbSTobias Grosser 23948fc6cdfbSTobias Grosser Linker L(*GPUModule); 23958fc6cdfbSTobias Grosser 23968fc6cdfbSTobias Grosser // Set an nvptx64 target triple to avoid linker warnings. The original 23978fc6cdfbSTobias Grosser // triple of the libdevice files are nvptx-unknown-unknown. 23988fc6cdfbSTobias Grosser LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 23998fc6cdfbSTobias Grosser L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 24008fc6cdfbSTobias Grosser } 24018fc6cdfbSTobias Grosser } 24028fc6cdfbSTobias Grosser 240357793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 240465d7f72fSSiddharth Bhat 24055857b701STobias Grosser if (verifyModule(*GPUModule)) { 240665d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 240765d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2408a0fb8b23SSiddharth Bhat DEBUG(dbgs() << "verifyModule Error:\n"; 2409a0fb8b23SSiddharth Bhat verifyModule(*GPUModule, &dbgs());); 241065d7f72fSSiddharth Bhat 241165d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 241265d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 241365d7f72fSSiddharth Bhat 24145857b701STobias Grosser BuildSuccessful = false; 24155857b701STobias Grosser return ""; 24165857b701STobias Grosser } 241732837fe3STobias Grosser 24188fc6cdfbSTobias Grosser addCUDALibDevice(); 24198fc6cdfbSTobias Grosser 242032837fe3STobias Grosser if (DumpKernelIR) 242132837fe3STobias Grosser outs() << *GPUModule << "\n"; 242232837fe3STobias Grosser 24232f3073b5SPhilipp Schaad if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 24249a18d559STobias Grosser // Optimize module. 24259a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 24269a18d559STobias Grosser PassManagerBuilder PassBuilder; 24279a18d559STobias Grosser PassBuilder.OptLevel = 3; 24289a18d559STobias Grosser PassBuilder.SizeLevel = 0; 24299a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 24309a18d559STobias Grosser OptPasses.run(*GPUModule); 24312f3073b5SPhilipp Schaad } 24329a18d559STobias Grosser 243374dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 243474dc3cb4STobias Grosser 243574dc3cb4STobias Grosser if (DumpKernelASM) 243674dc3cb4STobias Grosser outs() << Assembly << "\n"; 243774dc3cb4STobias Grosser 243832837fe3STobias Grosser GPUModule.release(); 2439472f9654STobias Grosser KernelIDs.clear(); 244057793596STobias Grosser 244157793596STobias Grosser return Assembly; 244232837fe3STobias Grosser } 2443eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2444eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an 2445eadf76d3SSiddharth Bhat /// `isl_pw_aff_list` from. We expect an rvalue ref because 2446eadf76d3SSiddharth Bhat /// all the isl_pw_aff are used up by this function. 2447eadf76d3SSiddharth Bhat /// 2448eadf76d3SSiddharth Bhat /// @returns The `isl_pw_aff_list`. 2449eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list * 2450eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context, 2451eadf76d3SSiddharth Bhat const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2452eadf76d3SSiddharth Bhat isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2453eadf76d3SSiddharth Bhat 2454eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2455eadf76d3SSiddharth Bhat List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2456eadf76d3SSiddharth Bhat } 2457eadf76d3SSiddharth Bhat return List; 2458eadf76d3SSiddharth Bhat } 2459eadf76d3SSiddharth Bhat 2460eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions. 2461eadf76d3SSiddharth Bhat /// 2462eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to 2463eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the 2464eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2465eadf76d3SSiddharth Bhat /// with the given `SeedSpace`. 2466eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions we want to align. 2467eadf76d3SSiddharth Bhat /// This is an rvalue reference because the entire vector is 2468eadf76d3SSiddharth Bhat /// used up by the end of the operation. 2469eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with. 2470eadf76d3SSiddharth Bhat /// @returns A std::pair, whose first element is the aligned space, 2471eadf76d3SSiddharth Bhat /// whose second element is the vector of aligned piecewise 2472eadf76d3SSiddharth Bhat /// affines. 2473eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2474eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2475eadf76d3SSiddharth Bhat __isl_take isl_space *SeedSpace) { 2476eadf76d3SSiddharth Bhat assert(SeedSpace && "Invalid seed space given."); 2477eadf76d3SSiddharth Bhat 2478eadf76d3SSiddharth Bhat isl_space *AlignSpace = SeedSpace; 2479eadf76d3SSiddharth Bhat for (isl_pw_aff *PwAff : PwAffs) { 2480eadf76d3SSiddharth Bhat isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2481eadf76d3SSiddharth Bhat AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2482eadf76d3SSiddharth Bhat } 2483eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AdjustedPwAffs; 2484eadf76d3SSiddharth Bhat 2485eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2486eadf76d3SSiddharth Bhat isl_pw_aff *Adjusted = PwAffs[i]; 2487eadf76d3SSiddharth Bhat assert(Adjusted && "Invalid pw_aff given."); 2488eadf76d3SSiddharth Bhat Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2489eadf76d3SSiddharth Bhat AdjustedPwAffs.push_back(Adjusted); 2490eadf76d3SSiddharth Bhat } 2491eadf76d3SSiddharth Bhat return std::make_pair(AlignSpace, AdjustedPwAffs); 2492eadf76d3SSiddharth Bhat } 249332837fe3STobias Grosser 24949dfe4e7cSTobias Grosser namespace { 24959dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 24969dfe4e7cSTobias Grosser public: 24979dfe4e7cSTobias Grosser static char ID; 24989dfe4e7cSTobias Grosser 249917f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 250017f01968SSiddharth Bhat 250117f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 250217f01968SSiddharth Bhat 2503e938517eSTobias Grosser /// The scop that is currently processed. 2504e938517eSTobias Grosser Scop *S; 2505e938517eSTobias Grosser 250638fc0aedSTobias Grosser LoopInfo *LI; 250738fc0aedSTobias Grosser DominatorTree *DT; 250838fc0aedSTobias Grosser ScalarEvolution *SE; 250938fc0aedSTobias Grosser const DataLayout *DL; 251038fc0aedSTobias Grosser RegionInfo *RI; 251138fc0aedSTobias Grosser 25129dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 25139dfe4e7cSTobias Grosser 2514e938517eSTobias Grosser /// Construct compilation options for PPCG. 2515e938517eSTobias Grosser /// 2516e938517eSTobias Grosser /// @returns The compilation options. 2517e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2518e938517eSTobias Grosser auto DebugOptions = 2519e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2520e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2521e938517eSTobias Grosser 2522e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2523e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2524e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2525e938517eSTobias Grosser DebugOptions->dump_sizes = false; 25268950ceadSTobias Grosser DebugOptions->verbose = false; 2527e938517eSTobias Grosser 2528e938517eSTobias Grosser Options->debug = DebugOptions; 2529e938517eSTobias Grosser 25309e3db2b7SSiddharth Bhat Options->group_chains = false; 2531e938517eSTobias Grosser Options->reschedule = true; 2532e938517eSTobias Grosser Options->scale_tile_loops = false; 2533e938517eSTobias Grosser Options->wrap = false; 2534e938517eSTobias Grosser 2535e938517eSTobias Grosser Options->non_negative_parameters = false; 2536e938517eSTobias Grosser Options->ctx = nullptr; 2537e938517eSTobias Grosser Options->sizes = nullptr; 2538e938517eSTobias Grosser 25399e3db2b7SSiddharth Bhat Options->tile = true; 25404eaedde5STobias Grosser Options->tile_size = 32; 25414eaedde5STobias Grosser 25429e3db2b7SSiddharth Bhat Options->isolate_full_tiles = false; 25439e3db2b7SSiddharth Bhat 2544130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2545b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2546b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2547e938517eSTobias Grosser 2548e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2549e938517eSTobias Grosser Options->openmp = false; 2550e938517eSTobias Grosser Options->linearize_device_arrays = true; 25519e3db2b7SSiddharth Bhat Options->allow_gnu_extensions = false; 2552e938517eSTobias Grosser 25539e3db2b7SSiddharth Bhat Options->unroll_copy_shared = false; 25549e3db2b7SSiddharth Bhat Options->unroll_gpu_tile = false; 25559e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25569e3db2b7SSiddharth Bhat 25579e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25589e3db2b7SSiddharth Bhat Options->hybrid = false; 2559e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2560e938517eSTobias Grosser Options->opencl_use_gpu = false; 2561e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2562e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2563e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2564e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2565e938517eSTobias Grosser 2566e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2567e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2568e938517eSTobias Grosser 2569e938517eSTobias Grosser return Options; 2570e938517eSTobias Grosser } 2571e938517eSTobias Grosser 2572f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2573f384594dSTobias Grosser /// 2574f384594dSTobias Grosser /// Instead of a normal access of the form: 2575f384594dSTobias Grosser /// 2576f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2577f384594dSTobias Grosser /// 2578f384594dSTobias Grosser /// a tagged access has the form 2579f384594dSTobias Grosser /// 2580f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2581f384594dSTobias Grosser /// 2582f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2583f384594dSTobias Grosser /// triggered the access. 2584f384594dSTobias Grosser /// 2585f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2586f384594dSTobias Grosser /// 2587f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2588f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2589b65ccc43STobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release()); 2590f384594dSTobias Grosser 2591f384594dSTobias Grosser for (auto &Stmt : *S) 2592f384594dSTobias Grosser for (auto &Acc : Stmt) 2593f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 25941515f6b9STobias Grosser isl_map *Relation = Acc->getAccessRelation().release(); 2595dcf8d696STobias Grosser Relation = 2596dcf8d696STobias Grosser isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2597f384594dSTobias Grosser 2598f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2599f384594dSTobias Grosser Space = isl_space_range(Space); 2600f384594dSTobias Grosser Space = isl_space_from_range(Space); 2601fe46c3ffSTobias Grosser Space = 2602fe46c3ffSTobias Grosser isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2603f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2604f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2605f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2606f384594dSTobias Grosser } 2607f384594dSTobias Grosser 2608f384594dSTobias Grosser return Accesses; 2609f384594dSTobias Grosser } 2610f384594dSTobias Grosser 2611f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2612f384594dSTobias Grosser /// 2613f384594dSTobias Grosser /// @see getTaggedAccesses 2614f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2615f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2616f384594dSTobias Grosser } 2617f384594dSTobias Grosser 2618f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2619f384594dSTobias Grosser /// 2620f384594dSTobias Grosser /// @see getTaggedAccesses 2621f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2622f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2623f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2624f384594dSTobias Grosser } 2625f384594dSTobias Grosser 2626f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2627f384594dSTobias Grosser /// 2628f384594dSTobias Grosser /// @see getTaggedAccesses 2629f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2630f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2631f384594dSTobias Grosser } 2632f384594dSTobias Grosser 2633aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2634aef5196fSTobias Grosser /// 2635aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2636aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2637aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2638aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2639aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2640aef5196fSTobias Grosser /// the data format that ppcg expects. 2641aef5196fSTobias Grosser /// 2642aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2643aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2644aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2645bd81a7eeSTobias Grosser S->getIslCtx(), 2646bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2647aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2648aef5196fSTobias Grosser 264925271b91STobias Grosser for (const SCEV *P : S->parameters()) { 26509a63570bSTobias Grosser isl_id *Id = S->getIdForParam(P).release(); 2651aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2652aef5196fSTobias Grosser } 2653aef5196fSTobias Grosser 2654aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 265577eef90fSTobias Grosser auto Id = Array->getBasePtrId().release(); 2656aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2657aef5196fSTobias Grosser } 2658aef5196fSTobias Grosser 2659aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2660aef5196fSTobias Grosser 2661aef5196fSTobias Grosser return Names; 2662aef5196fSTobias Grosser } 2663aef5196fSTobias Grosser 2664e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2665e938517eSTobias Grosser /// 2666f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2667f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2668f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2669f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2670e938517eSTobias Grosser /// 2671e938517eSTobias Grosser /// @returns A new ppcg scop. 2672e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 26739e3db2b7SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 26749e3db2b7SSiddharth Bhat 2675e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2676e938517eSTobias Grosser 2677e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2678a82f2d26SSiddharth Bhat // enable live range reordering 2679a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2680e938517eSTobias Grosser 2681e938517eSTobias Grosser PPCGScop->start = 0; 2682e938517eSTobias Grosser PPCGScop->end = 0; 2683e938517eSTobias Grosser 26848ea1fc19STobias Grosser PPCGScop->context = S->getContext().release(); 268531df6f31STobias Grosser PPCGScop->domain = S->getDomains().release(); 26869e3db2b7SSiddharth Bhat // TODO: investigate this further. PPCG calls collect_call_domains. 26878ea1fc19STobias Grosser PPCGScop->call = isl_union_set_from_set(S->getContext().release()); 2688f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 26895ab39ff2STobias Grosser PPCGScop->reads = S->getReads().release(); 2690e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2691f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 26925ab39ff2STobias Grosser PPCGScop->may_writes = S->getWrites().release(); 2693f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 26945ab39ff2STobias Grosser PPCGScop->must_writes = S->getMustWrites().release(); 2695e938517eSTobias Grosser PPCGScop->live_out = nullptr; 26969e3db2b7SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 26979e3db2b7SSiddharth Bhat PPCGScop->must_kills = KillsInfo.MustKills.take(); 26989e3db2b7SSiddharth Bhat 2699e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2700a82f2d26SSiddharth Bhat PPCGScop->independence = 2701a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2702e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2703e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2704e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2705e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2706e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2707e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2708e938517eSTobias Grosser 270961bd3a48STobias Grosser PPCGScop->schedule = S->getScheduleTree().release(); 2710a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2711a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2712a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2713a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2714a82f2d26SSiddharth Bhat 2715a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2716e938517eSTobias Grosser PPCGScop->pet = nullptr; 2717e938517eSTobias Grosser 2718f384594dSTobias Grosser compute_tagger(PPCGScop); 2719f384594dSTobias Grosser compute_dependences(PPCGScop); 27209e3db2b7SSiddharth Bhat eliminate_dead_code(PPCGScop); 2721f384594dSTobias Grosser 2722e938517eSTobias Grosser return PPCGScop; 2723e938517eSTobias Grosser } 2724e938517eSTobias Grosser 2725a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 272660f63b49STobias Grosser /// 272760f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 272860f63b49STobias Grosser /// 272960f63b49STobias Grosser /// @returns A list of array accesses. 273060f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 273160f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 273260f63b49STobias Grosser 273360f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 273460f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 273560f63b49STobias Grosser Access->read = Acc->isRead(); 273660f63b49STobias Grosser Access->write = Acc->isWrite(); 27371515f6b9STobias Grosser Access->access = Acc->getAccessRelation().release(); 273860f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 273960f63b49STobias Grosser Space = isl_space_range(Space); 274060f63b49STobias Grosser Space = isl_space_from_range(Space); 2741fe46c3ffSTobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 274260f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 274360f63b49STobias Grosser Access->tagged_access = 27441515f6b9STobias Grosser isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2745b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 2746fe46c3ffSTobias Grosser Access->ref_id = Acc->getId().release(); 274760f63b49STobias Grosser Access->next = Accesses; 2748b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2749ecb94a03STobias Grosser // TODO: Also mark one-element accesses to arrays as fixed-element. 2750ecb94a03STobias Grosser Access->fixed_element = 2751ecb94a03STobias Grosser Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false; 275260f63b49STobias Grosser Accesses = Access; 275360f63b49STobias Grosser } 275460f63b49STobias Grosser 275560f63b49STobias Grosser return Accesses; 275660f63b49STobias Grosser } 275760f63b49STobias Grosser 275869b46751STobias Grosser /// Collect the list of GPU statements. 275969b46751STobias Grosser /// 276069b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 276169b46751STobias Grosser /// as well as a list with all memory accesses. 276269b46751STobias Grosser /// 276369b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 276469b46751STobias Grosser /// 276569b46751STobias Grosser /// @returns A linked-list of statements. 276669b46751STobias Grosser gpu_stmt *getStatements() { 276769b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 276869b46751STobias Grosser std::distance(S->begin(), S->end())); 276969b46751STobias Grosser 277069b46751STobias Grosser int i = 0; 277169b46751STobias Grosser for (auto &Stmt : *S) { 277269b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 277369b46751STobias Grosser 2774dcf8d696STobias Grosser GPUStmt->id = Stmt.getDomainId().release(); 277569b46751STobias Grosser 277669b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 277769b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 277860f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 277969b46751STobias Grosser i++; 278069b46751STobias Grosser } 278169b46751STobias Grosser 278269b46751STobias Grosser return Stmts; 278369b46751STobias Grosser } 278469b46751STobias Grosser 278560f63b49STobias Grosser /// Derive the extent of an array. 278660f63b49STobias Grosser /// 2787d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2788d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2789d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2790d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2791d58acf86STobias Grosser /// subscript value for the first dimension. 279260f63b49STobias Grosser /// 279360f63b49STobias Grosser /// @param Array The array to derive the extent for. 279460f63b49STobias Grosser /// 279560f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 2796d2e57981STobias Grosser isl::set getExtent(ScopArrayInfo *Array) { 2797d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 2798fa03cb76STobias Grosser 2799fa03cb76STobias Grosser if (Array->getNumberOfDimensions() == 0) 2800fa03cb76STobias Grosser return isl::set::universe(Array->getSpace()); 2801fa03cb76STobias Grosser 2802fa03cb76STobias Grosser isl::union_map Accesses = S->getAccesses(Array); 2803d2e57981STobias Grosser isl::union_set AccessUSet = Accesses.range(); 2804d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2805d2e57981STobias Grosser AccessUSet = AccessUSet.detect_equalities(); 2806d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2807d58acf86STobias Grosser 2808d2e57981STobias Grosser if (AccessUSet.is_empty()) 2809d2e57981STobias Grosser return isl::set::empty(Array->getSpace()); 2810d58acf86STobias Grosser 2811d2e57981STobias Grosser isl::set AccessSet = AccessUSet.extract_set(Array->getSpace()); 281260f63b49STobias Grosser 2813d2e57981STobias Grosser isl::local_space LS = isl::local_space(Array->getSpace()); 2814d58acf86STobias Grosser 2815d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0); 2816d2e57981STobias Grosser isl::pw_aff OuterMin = AccessSet.dim_min(0); 2817d2e57981STobias Grosser isl::pw_aff OuterMax = AccessSet.dim_max(0); 2818d2e57981STobias Grosser OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2819d2e57981STobias Grosser OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2820d2e57981STobias Grosser OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2821d2e57981STobias Grosser OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2822d58acf86STobias Grosser 2823d2e57981STobias Grosser isl::set Extent = isl::set::universe(Array->getSpace()); 2824d58acf86STobias Grosser 2825d2e57981STobias Grosser Extent = Extent.intersect(OuterMin.le_set(Val)); 2826d2e57981STobias Grosser Extent = Extent.intersect(OuterMax.ge_set(Val)); 2827d58acf86STobias Grosser 2828d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2829d2e57981STobias Grosser Extent = Extent.lower_bound_si(isl::dim::set, i, 0); 2830d58acf86STobias Grosser 2831b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2832d2e57981STobias Grosser isl::pw_aff PwAff = Array->getDimensionSizePw(i); 2833b7f68b8cSSiddharth Bhat 2834b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2835b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2836d2e57981STobias Grosser if (PwAff.is_null()) { 2837b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2838b7f68b8cSSiddharth Bhat continue; 2839b7f68b8cSSiddharth Bhat } 2840b7f68b8cSSiddharth Bhat 2841d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain( 2842d2e57981STobias Grosser isl::local_space(Array->getSpace()), isl::dim::set, i); 2843d2e57981STobias Grosser PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2844d2e57981STobias Grosser PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in)); 2845d2e57981STobias Grosser isl::set Set = PwAff.gt_set(Val); 2846d2e57981STobias Grosser Extent = Set.intersect(Extent); 2847d58acf86STobias Grosser } 2848d58acf86STobias Grosser 2849d58acf86STobias Grosser return Extent; 285060f63b49STobias Grosser } 285160f63b49STobias Grosser 285260f63b49STobias Grosser /// Derive the bounds of an array. 285360f63b49STobias Grosser /// 285460f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 285560f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 285660f63b49STobias Grosser /// ScopArrayInfo. 285760f63b49STobias Grosser /// 285860f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 285960f63b49STobias Grosser /// @param Array The polly array from which to take the information. 286060f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2861eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> Bounds; 28629e3db2b7SSiddharth Bhat 286360f63b49STobias Grosser if (PPCGArray.n_index > 0) { 286402293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 286502293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 286602293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 286702293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 286802293ed7STobias Grosser isl_set_free(Dom); 28699e3db2b7SSiddharth Bhat isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2870eadf76d3SSiddharth Bhat Bounds.push_back(Zero); 287102293ed7STobias Grosser } else { 287260f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 287360f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 287460f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 287560f63b49STobias Grosser isl_set_free(Dom); 287660f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 287702293ed7STobias Grosser isl_local_space *LS = 287802293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 287960f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 288060f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 288160f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 28828ea1fc19STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext().release()); 2883eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 288460f63b49STobias Grosser } 288502293ed7STobias Grosser } 288660f63b49STobias Grosser 288760f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 288877eef90fSTobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 288960f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 289060f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 289160f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2892eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 289360f63b49STobias Grosser } 28949e3db2b7SSiddharth Bhat 2895eadf76d3SSiddharth Bhat /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2896eadf76d3SSiddharth Bhat /// to have the same parameter dimensions. So, we need to align them to an 2897eadf76d3SSiddharth Bhat /// appropriate space. 2898eadf76d3SSiddharth Bhat /// Scop::Context is _not_ an appropriate space, because when we have 2899eadf76d3SSiddharth Bhat /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 2900eadf76d3SSiddharth Bhat /// contain all parameter dimensions. 2901eadf76d3SSiddharth Bhat /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 2902b65ccc43STobias Grosser isl_space *SeedAlignSpace = S->getParamSpace().release(); 2903eadf76d3SSiddharth Bhat SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 2904eadf76d3SSiddharth Bhat 2905eadf76d3SSiddharth Bhat isl_space *AlignSpace = nullptr; 2906eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AlignedBounds; 2907eadf76d3SSiddharth Bhat std::tie(AlignSpace, AlignedBounds) = 2908eadf76d3SSiddharth Bhat alignPwAffs(std::move(Bounds), SeedAlignSpace); 2909eadf76d3SSiddharth Bhat 2910eadf76d3SSiddharth Bhat assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 2911eadf76d3SSiddharth Bhat 2912eadf76d3SSiddharth Bhat isl_pw_aff_list *BoundsList = 2913eadf76d3SSiddharth Bhat createPwAffList(S->getIslCtx(), std::move(AlignedBounds)); 2914eadf76d3SSiddharth Bhat 29159e3db2b7SSiddharth Bhat isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2916eadf76d3SSiddharth Bhat BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 29179e3db2b7SSiddharth Bhat 29189e3db2b7SSiddharth Bhat assert(BoundsSpace && "Unable to access space of array."); 29199e3db2b7SSiddharth Bhat assert(BoundsList && "Unable to access list of bounds."); 29209e3db2b7SSiddharth Bhat 29219e3db2b7SSiddharth Bhat PPCGArray.bound = 29229e3db2b7SSiddharth Bhat isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 29239e3db2b7SSiddharth Bhat assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 292460f63b49STobias Grosser } 292560f63b49STobias Grosser 292660f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 292760f63b49STobias Grosser /// 292860f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 292943f178bbSSiddharth Bhat void createArrays(gpu_prog *PPCGProg, 293043f178bbSSiddharth Bhat const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 293160f63b49STobias Grosser int i = 0; 293243f178bbSSiddharth Bhat for (auto &Array : ValidSAIs) { 293360f63b49STobias Grosser std::string TypeName; 293460f63b49STobias Grosser raw_string_ostream OS(TypeName); 293560f63b49STobias Grosser 293660f63b49STobias Grosser OS << *Array->getElementType(); 293760f63b49STobias Grosser TypeName = OS.str(); 293860f63b49STobias Grosser 293960f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 294060f63b49STobias Grosser 294177eef90fSTobias Grosser PPCGArray.space = Array->getSpace().release(); 294260f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 294334eeabbcSSiddharth Bhat PPCGArray.size = DL->getTypeAllocSize(Array->getElementType()); 294460f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 294560f63b49STobias Grosser PPCGArray.extent = nullptr; 294660f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 2947d2e57981STobias Grosser PPCGArray.extent = getExtent(Array).release(); 294860f63b49STobias Grosser PPCGArray.n_ref = 0; 294960f63b49STobias Grosser PPCGArray.refs = nullptr; 295060f63b49STobias Grosser PPCGArray.accessed = true; 2951fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2952fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 295360f63b49STobias Grosser PPCGArray.has_compound_element = false; 295460f63b49STobias Grosser PPCGArray.local = false; 295560f63b49STobias Grosser PPCGArray.declare_local = false; 295660f63b49STobias Grosser PPCGArray.global = false; 295760f63b49STobias Grosser PPCGArray.linearize = false; 295860f63b49STobias Grosser PPCGArray.dep_order = nullptr; 295913c78e4dSTobias Grosser PPCGArray.user = Array; 296060f63b49STobias Grosser 29619e3db2b7SSiddharth Bhat PPCGArray.bound = nullptr; 296260f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 29632d010dafSTobias Grosser i++; 2964b9fc860aSTobias Grosser 2965b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 2966ecb94a03STobias Grosser PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray); 296760f63b49STobias Grosser } 296860f63b49STobias Grosser } 296960f63b49STobias Grosser 297060f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 297160f63b49STobias Grosser /// 297260f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 297360f63b49STobias Grosser isl_union_map *getArrayIdentity() { 2974b65ccc43STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release()); 297560f63b49STobias Grosser 2976d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 297777eef90fSTobias Grosser isl_space *Space = Array->getSpace().release(); 297860f63b49STobias Grosser Space = isl_space_map_from_set(Space); 297960f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 298060f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 298160f63b49STobias Grosser } 298260f63b49STobias Grosser 298360f63b49STobias Grosser return Maps; 298460f63b49STobias Grosser } 298560f63b49STobias Grosser 2986e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2987e938517eSTobias Grosser /// 2988a6d48f59SMichael Kruse /// @returns A new gpu program description. 2989e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2990e938517eSTobias Grosser 2991e938517eSTobias Grosser if (!PPCGScop) 2992e938517eSTobias Grosser return nullptr; 2993e938517eSTobias Grosser 2994e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2995e938517eSTobias Grosser 2996e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2997e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2998aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 299960f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 300060f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 300160f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 300260f63b49STobias Grosser PPCGProg->tagged_must_kill = 300360f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 300460f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 300560f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 30069e3db2b7SSiddharth Bhat // TODO: verify that this assignment is correct. 3007e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 300869b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 300969b46751STobias Grosser PPCGProg->stmts = getStatements(); 301043f178bbSSiddharth Bhat 301143f178bbSSiddharth Bhat // Only consider arrays that have a non-empty extent. 301243f178bbSSiddharth Bhat // Otherwise, this will cause us to consider the following kinds of 301343f178bbSSiddharth Bhat // empty arrays: 301443f178bbSSiddharth Bhat // 1. Invariant loads that are represented by SAI objects. 301543f178bbSSiddharth Bhat // 2. Arrays with statically known zero size. 301643f178bbSSiddharth Bhat auto ValidSAIsRange = 301743f178bbSSiddharth Bhat make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 3018d2e57981STobias Grosser return !getExtent(SAI).is_empty(); 301943f178bbSSiddharth Bhat }); 302043f178bbSSiddharth Bhat SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 302143f178bbSSiddharth Bhat ValidSAIsRange.end()); 302243f178bbSSiddharth Bhat 302343f178bbSSiddharth Bhat PPCGProg->n_array = 302443f178bbSSiddharth Bhat ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 302560f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 302660f63b49STobias Grosser PPCGProg->n_array); 302760f63b49STobias Grosser 302843f178bbSSiddharth Bhat createArrays(PPCGProg, ValidSAIs); 3029e938517eSTobias Grosser 3030ecb94a03STobias Grosser PPCGProg->array_order = nullptr; 3031ecb94a03STobias Grosser collect_order_dependences(PPCGProg); 3032ecb94a03STobias Grosser 3033d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 3034e938517eSTobias Grosser return PPCGProg; 3035e938517eSTobias Grosser } 3036e938517eSTobias Grosser 303769b46751STobias Grosser struct PrintGPUUserData { 303869b46751STobias Grosser struct cuda_info *CudaInfo; 303969b46751STobias Grosser struct gpu_prog *PPCGProg; 304069b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 304169b46751STobias Grosser }; 304269b46751STobias Grosser 304369b46751STobias Grosser /// Print a user statement node in the host code. 304469b46751STobias Grosser /// 304569b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 304669b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 304769b46751STobias Grosser /// host ast. 304869b46751STobias Grosser /// 304969b46751STobias Grosser /// @param P The printer to print to 305069b46751STobias Grosser /// @param Options The printing options to use 305169b46751STobias Grosser /// @param Node The node to print 305269b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 305369b46751STobias Grosser /// expected to be of type PrintGPUUserData. 305469b46751STobias Grosser /// 305569b46751STobias Grosser /// @returns A printer to which the output has been printed. 305669b46751STobias Grosser static __isl_give isl_printer * 305769b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 305869b46751STobias Grosser __isl_take isl_ast_print_options *Options, 305969b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 306069b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 306169b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 306269b46751STobias Grosser 306369b46751STobias Grosser if (Id) { 306420251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 306520251734STobias Grosser 306620251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 306720251734STobias Grosser // otherwise try to call pet functionality that is not available in 306820251734STobias Grosser // Polly. 306920251734STobias Grosser if (IsUser) { 307020251734STobias Grosser P = isl_printer_start_line(P); 307120251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 307220251734STobias Grosser P = isl_printer_end_line(P); 307320251734STobias Grosser isl_id_free(Id); 307420251734STobias Grosser isl_ast_print_options_free(Options); 307520251734STobias Grosser return P; 307620251734STobias Grosser } 307720251734STobias Grosser 307869b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 307969b46751STobias Grosser isl_id_free(Id); 308069b46751STobias Grosser Data->Kernels.push_back(Kernel); 308169b46751STobias Grosser } 308269b46751STobias Grosser 308369b46751STobias Grosser return print_host_user(P, Options, Node, User); 308469b46751STobias Grosser } 308569b46751STobias Grosser 308669b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 308769b46751STobias Grosser /// 308869b46751STobias Grosser /// @param Kernel The kernel to print 308969b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 309069b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 309169b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 309269b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 309369b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 309469b46751STobias Grosser char *String = isl_printer_get_str(P); 309569b46751STobias Grosser printf("%s\n", String); 309669b46751STobias Grosser free(String); 309769b46751STobias Grosser isl_printer_free(P); 309869b46751STobias Grosser } 309969b46751STobias Grosser 310069b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 310169b46751STobias Grosser /// 310269b46751STobias Grosser /// @param Tree An AST describing GPU code 310369b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 310469b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 310569b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 310669b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 310769b46751STobias Grosser 310869b46751STobias Grosser PrintGPUUserData Data; 310969b46751STobias Grosser Data.PPCGProg = PPCGProg; 311069b46751STobias Grosser 311169b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 311269b46751STobias Grosser Options = 311369b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 311469b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 311569b46751STobias Grosser char *String = isl_printer_get_str(P); 311669b46751STobias Grosser printf("# host\n"); 311769b46751STobias Grosser printf("%s\n", String); 311869b46751STobias Grosser free(String); 311969b46751STobias Grosser isl_printer_free(P); 312069b46751STobias Grosser 312169b46751STobias Grosser for (auto Kernel : Data.Kernels) { 312269b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 312369b46751STobias Grosser printKernel(Kernel); 312469b46751STobias Grosser } 312569b46751STobias Grosser } 312669b46751STobias Grosser 3127f384594dSTobias Grosser // Generate a GPU program using PPCG. 3128f384594dSTobias Grosser // 3129f384594dSTobias Grosser // GPU mapping consists of multiple steps: 3130f384594dSTobias Grosser // 3131f384594dSTobias Grosser // 1) Compute new schedule for the program. 3132f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 3133f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 3134f384594dSTobias Grosser // 3135f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3136f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3137f384594dSTobias Grosser // strategy directly from this pass. 3138f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3139f384594dSTobias Grosser 3140f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 3141f384594dSTobias Grosser 3142f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 3143f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 3144f384594dSTobias Grosser PPCGGen->print = nullptr; 3145f384594dSTobias Grosser PPCGGen->print_user = nullptr; 314660c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3147f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 3148f384594dSTobias Grosser PPCGGen->tree = nullptr; 3149f384594dSTobias Grosser PPCGGen->types.n = 0; 3150f384594dSTobias Grosser PPCGGen->types.name = nullptr; 3151f384594dSTobias Grosser PPCGGen->sizes = nullptr; 3152f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 3153f384594dSTobias Grosser PPCGGen->kernel_id = 0; 3154f384594dSTobias Grosser 3155f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 3156f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3157f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 31582341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3159f384594dSTobias Grosser 3160f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 3161f384594dSTobias Grosser 3162e32498c9STobias Grosser int has_permutable = has_any_permutable_node(Schedule); 3163e32498c9STobias Grosser 3164b5563c68STobias Grosser Schedule = 3165b5563c68STobias Grosser isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3166b5563c68STobias Grosser 316769b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 3168aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 3169638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3170638316daSSiddharth Bhat << " does not have permutable bands. Bailing out\n";); 317169b46751STobias Grosser } else { 3172861a387fSTobias Grosser const bool CreateTransferToFromDevice = !PollyManagedMemory; 3173861a387fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice); 317469b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 317569b46751STobias Grosser } 3176aef5196fSTobias Grosser 3177f384594dSTobias Grosser if (DumpSchedule) { 3178f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 3179f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3180f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 3181f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 3182f384594dSTobias Grosser if (Schedule) 3183f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 3184f384594dSTobias Grosser else 3185f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 3186f384594dSTobias Grosser 3187f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 3188f384594dSTobias Grosser isl_printer_free(P); 3189f384594dSTobias Grosser } 3190f384594dSTobias Grosser 319169b46751STobias Grosser if (DumpCode) { 319269b46751STobias Grosser printf("Code\n"); 319369b46751STobias Grosser printf("====\n"); 319469b46751STobias Grosser if (PPCGGen->tree) 319569b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 319669b46751STobias Grosser else 319769b46751STobias Grosser printf("No code generated\n"); 319869b46751STobias Grosser } 319969b46751STobias Grosser 3200f384594dSTobias Grosser isl_schedule_free(Schedule); 3201f384594dSTobias Grosser 3202f384594dSTobias Grosser return PPCGGen; 3203f384594dSTobias Grosser } 3204f384594dSTobias Grosser 3205f384594dSTobias Grosser /// Free gpu_gen structure. 3206f384594dSTobias Grosser /// 3207f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 3208f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 3209f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 3210f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 3211f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 3212f384594dSTobias Grosser free(PPCGGen); 3213f384594dSTobias Grosser } 3214f384594dSTobias Grosser 3215b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 3216b307ed4dSTobias Grosser /// 3217b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 3218b307ed4dSTobias Grosser /// ourselves. 3219b307ed4dSTobias Grosser /// 3220b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 3221b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 3222b307ed4dSTobias Grosser free(PPCGScop->options->debug); 3223b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 3224b307ed4dSTobias Grosser free(PPCGScop->options); 3225b307ed4dSTobias Grosser PPCGScop->options = nullptr; 3226b307ed4dSTobias Grosser } 3227b307ed4dSTobias Grosser 322882f2af35STobias Grosser /// Approximate the number of points in the set. 322982f2af35STobias Grosser /// 323082f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 323182f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 323282f2af35STobias Grosser /// 323382f2af35STobias Grosser /// @param Set The set to count. 323482f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 323582f2af35STobias Grosser /// expression. 323682f2af35STobias Grosser /// 323782f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 323882f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 323982f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 324082f2af35STobias Grosser 324182f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 324282f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 324382f2af35STobias Grosser 324482f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 324582f2af35STobias Grosser Space = isl_space_params(Space); 324682f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 324782f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 324882f2af35STobias Grosser 324982f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 325082f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 325182f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 325282f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 325382f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 325482f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 325582f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 325682f2af35STobias Grosser } 325782f2af35STobias Grosser 325882f2af35STobias Grosser isl_set_free(Set); 325982f2af35STobias Grosser isl_pw_aff_free(OneAff); 326082f2af35STobias Grosser 326182f2af35STobias Grosser return Expr; 326282f2af35STobias Grosser } 326382f2af35STobias Grosser 326482f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 326582f2af35STobias Grosser /// statement. 326682f2af35STobias Grosser /// 326782f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 326882f2af35STobias Grosser /// instructions. 326982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 327082f2af35STobias Grosser /// expression. 327182f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 327282f2af35STobias Grosser /// by @p Stmt. 327382f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 327482f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 3275dcf8d696STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 327682f2af35STobias Grosser 327782f2af35STobias Grosser long InstCount = 0; 327882f2af35STobias Grosser 327982f2af35STobias Grosser if (Stmt.isBlockStmt()) { 328082f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 328182f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 328282f2af35STobias Grosser } else { 328382f2af35STobias Grosser auto *R = Stmt.getRegion(); 328482f2af35STobias Grosser 328582f2af35STobias Grosser for (auto *BB : R->blocks()) { 328682f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 328782f2af35STobias Grosser } 328882f2af35STobias Grosser } 328982f2af35STobias Grosser 329082f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 329182f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 329282f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 329382f2af35STobias Grosser } 329482f2af35STobias Grosser 329582f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 329682f2af35STobias Grosser /// 329782f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 329882f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 329982f2af35STobias Grosser /// expression. 330082f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 330182f2af35STobias Grosser /// in @p S. 330282f2af35STobias Grosser __isl_give isl_ast_expr * 330382f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 330482f2af35STobias Grosser isl_ast_expr *Instructions; 330582f2af35STobias Grosser 330682f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 330782f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 330882f2af35STobias Grosser 330982f2af35STobias Grosser for (ScopStmt &Stmt : S) { 331082f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 331182f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 331282f2af35STobias Grosser } 331382f2af35STobias Grosser return Instructions; 331482f2af35STobias Grosser } 331582f2af35STobias Grosser 331682f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 331782f2af35STobias Grosser /// 331882f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 331982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 332082f2af35STobias Grosser /// expression. 332182f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 332282f2af35STobias Grosser /// compute and to FALSE, otherwise. 332382f2af35STobias Grosser __isl_give isl_ast_expr * 332482f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 332582f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 332682f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 332782f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 332882f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 332982f2af35STobias Grosser } 333082f2af35STobias Grosser 3331f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 3332f291c8d5SSiddharth Bhat /// kernels. 3333f291c8d5SSiddharth Bhat /// 3334f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 3335f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 33368fc6cdfbSTobias Grosser bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 33378fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 3338f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 3339f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 33408fc6cdfbSTobias Grosser if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 33418fc6cdfbSTobias Grosser AllowCUDALibDevice)) { 3342f291c8d5SSiddharth Bhat continue; 3343f291c8d5SSiddharth Bhat } 3344f291c8d5SSiddharth Bhat 3345bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 3346bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3347bccaea57SSiddharth Bhat if (!p) 3348bccaea57SSiddharth Bhat continue; 3349bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 3350bccaea57SSiddharth Bhat return true; 3351bccaea57SSiddharth Bhat } 3352f291c8d5SSiddharth Bhat } 3353bccaea57SSiddharth Bhat return false; 3354bccaea57SSiddharth Bhat } 3355bccaea57SSiddharth Bhat 3356f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 33578fc6cdfbSTobias Grosser bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3358bccaea57SSiddharth Bhat for (auto &Stmt : S) { 3359bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 33608fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 33618fc6cdfbSTobias Grosser AllowCUDALibDevice)) 3362bccaea57SSiddharth Bhat return true; 3363bccaea57SSiddharth Bhat } else { 3364bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 3365bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 3366bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 33678fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3368bccaea57SSiddharth Bhat return true; 3369bccaea57SSiddharth Bhat } 3370bccaea57SSiddharth Bhat } 3371bccaea57SSiddharth Bhat return false; 3372bccaea57SSiddharth Bhat } 3373bccaea57SSiddharth Bhat 337438fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 337538fc0aedSTobias Grosser /// 337632837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 337732837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 337832837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 337938fc0aedSTobias Grosser ScopAnnotator Annotator; 338038fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 338138fc0aedSTobias Grosser 338238fc0aedSTobias Grosser Region *R = &S->getRegion(); 338338fc0aedSTobias Grosser 338438fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 338538fc0aedSTobias Grosser 338638fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 338738fc0aedSTobias Grosser 338838fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 338938fc0aedSTobias Grosser 339038fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 339138fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 339238fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 339338fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 339438fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 339538fc0aedSTobias Grosser // code generating this scop. 339603346c27SSiddharth Bhat BBPair StartExitBlocks; 339703346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 339803346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 33992d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3400256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 340138fc0aedSTobias Grosser 340203346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 340303346c27SSiddharth Bhat 34042d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 340517f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 3406acf80064SEli Friedman 340738fc0aedSTobias Grosser // TODO: Handle LICM 340838fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 340938fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 3410cb1aef8dSTobias Grosser 3411cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 34122b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 341382f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 341482f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 3415cb1aef8dSTobias Grosser isl_ast_build_free(Build); 3416cb1aef8dSTobias Grosser 34179e3db2b7SSiddharth Bhat // preload invariant loads. Note: This should happen before the RTC 34189e3db2b7SSiddharth Bhat // because the RTC may depend on values that are invariant load hoisted. 341971dfb3ebSSiddharth Bhat if (!NodeBuilder.preloadInvariantLoads()) { 342071dfb3ebSSiddharth Bhat DEBUG(dbgs() << "preloading invariant loads failed in function: " + 34214ebeb356SSiddharth Bhat S->getFunction().getName() + 34224ebeb356SSiddharth Bhat " | Scop Region: " + S->getNameStr()); 342371dfb3ebSSiddharth Bhat // adjust the dominator tree accordingly. 342471dfb3ebSSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 342571dfb3ebSSiddharth Bhat assert(ExitingBlock); 342671dfb3ebSSiddharth Bhat auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 342771dfb3ebSSiddharth Bhat assert(MergeBlock); 342871dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*StartBlock, Builder); 342971dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*ExitingBlock, Builder); 343071dfb3ebSSiddharth Bhat auto *ExitingBB = S->getExitingBlock(); 343171dfb3ebSSiddharth Bhat assert(ExitingBB); 34329e3db2b7SSiddharth Bhat 343371dfb3ebSSiddharth Bhat DT->changeImmediateDominator(MergeBlock, ExitingBB); 343471dfb3ebSSiddharth Bhat DT->eraseNode(ExitingBlock); 343571dfb3ebSSiddharth Bhat isl_ast_expr_free(Condition); 343671dfb3ebSSiddharth Bhat isl_ast_node_free(Root); 343771dfb3ebSSiddharth Bhat } else { 343871dfb3ebSSiddharth Bhat 3439*7b9f5ca2SSiddharth Bhat if (polly::PerfMonitoring) { 3440*7b9f5ca2SSiddharth Bhat PerfMonitor P(*S, EnteringBB->getParent()->getParent()); 3441*7b9f5ca2SSiddharth Bhat P.initialize(); 3442*7b9f5ca2SSiddharth Bhat P.insertRegionStart(SplitBlock->getTerminator()); 3443*7b9f5ca2SSiddharth Bhat 3444*7b9f5ca2SSiddharth Bhat // TODO: actually think if this is the correct exiting block to place 3445*7b9f5ca2SSiddharth Bhat // the `end` performance marker. Invariant load hoisting changes 3446*7b9f5ca2SSiddharth Bhat // the CFG in a way that I do not precisely understand, so I 3447*7b9f5ca2SSiddharth Bhat // (Siddharth<[email protected]>) should come back to this and 3448*7b9f5ca2SSiddharth Bhat // think about which exiting block to use. 3449*7b9f5ca2SSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 3450*7b9f5ca2SSiddharth Bhat assert(ExitingBlock); 3451*7b9f5ca2SSiddharth Bhat BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor(); 3452*7b9f5ca2SSiddharth Bhat P.insertRegionEnd(MergeBlock->getTerminator()); 3453*7b9f5ca2SSiddharth Bhat } 3454*7b9f5ca2SSiddharth Bhat 345571dfb3ebSSiddharth Bhat NodeBuilder.addParameters(S->getContext().release()); 3456cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 3457cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3458cb1aef8dSTobias Grosser 345938fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 3460fa7b0802STobias Grosser 346138fc0aedSTobias Grosser NodeBuilder.create(Root); 346271dfb3ebSSiddharth Bhat } 34635857b701STobias Grosser 3464bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 3465bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3466de244eb4STobias Grosser /// point in running it on a GPU. 3467bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 346803346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 3469bc653f20STobias Grosser 34705857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 347103346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 347238fc0aedSTobias Grosser } 347338fc0aedSTobias Grosser 3474e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 3475e938517eSTobias Grosser S = &CurrentScop; 347638fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 347738fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 347838fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 34797b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 348038fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3481e938517eSTobias Grosser 3482656e6295SSiddharth Bhat DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S) 3483656e6295SSiddharth Bhat << " | loop depth: " << S->getMaxLoopDepth() << "\n"); 3484656e6295SSiddharth Bhat 3485f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 3486f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 3487f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 3488bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 3489bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 34908fc6cdfbSTobias Grosser if (containsInvalidKernelFunction(CurrentScop, 34918fc6cdfbSTobias Grosser Architecture == GPUArch::NVPTX64)) { 3492f291c8d5SSiddharth Bhat DEBUG( 3493638316daSSiddharth Bhat dbgs() << getUniqueScopName(S) 3494638316daSSiddharth Bhat << " contains function which cannot be materialised in a GPU " 3495f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3496bccaea57SSiddharth Bhat return false; 3497f291c8d5SSiddharth Bhat } 3498bccaea57SSiddharth Bhat 3499e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3500e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3501f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 350238fc0aedSTobias Grosser 350302ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 350432837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 350502ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 3506638316daSSiddharth Bhat } else { 3507638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3508638316daSSiddharth Bhat << " has empty PPCGGen->tree. Bailing out.\n"); 350902ca346eSSingapuram Sanjay Srivallabh } 351038fc0aedSTobias Grosser 3511b307ed4dSTobias Grosser freeOptions(PPCGScop); 3512f384594dSTobias Grosser freePPCGGen(PPCGGen); 3513e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3514e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3515e938517eSTobias Grosser 3516e938517eSTobias Grosser return true; 3517e938517eSTobias Grosser } 35189dfe4e7cSTobias Grosser 35199dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 35209dfe4e7cSTobias Grosser 35219dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 35229dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 35239dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 35249dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 35255cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 35269dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 35279dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 35289dfe4e7cSTobias Grosser 35299dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 35309dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 35319dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 35329dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 35339dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 35345cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 35359dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 35369dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 35379dfe4e7cSTobias Grosser 35389dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 35399dfe4e7cSTobias Grosser // region tree. 35409dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 35419dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 35429dfe4e7cSTobias Grosser } 35439dfe4e7cSTobias Grosser }; 354424222c73STobias Grosser } // namespace 35459dfe4e7cSTobias Grosser 35469dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 35479dfe4e7cSTobias Grosser 354817f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 354917f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 355017f01968SSiddharth Bhat generator->Runtime = Runtime; 355117f01968SSiddharth Bhat generator->Architecture = Arch; 355217f01968SSiddharth Bhat return generator; 355317f01968SSiddharth Bhat } 35549dfe4e7cSTobias Grosser 35559dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 35569dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 35579dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 35589dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 35599dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 35609dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 35619dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 35625cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 35639dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 35649dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3565