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" 1938fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 209dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 219dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 22f384594dSTobias Grosser #include "polly/Options.h" 23629109b6STobias Grosser #include "polly/ScopDetection.h" 249dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 25edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2674dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 309dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3274dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3374dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 34e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 358fc6cdfbSTobias Grosser #include "llvm/IRReader/IRReader.h" 368fc6cdfbSTobias Grosser #include "llvm/Linker/Linker.h" 3774dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3874dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3974dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 409a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 41750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 429dfe4e7cSTobias Grosser 43f384594dSTobias Grosser #include "isl/union_map.h" 44f384594dSTobias Grosser 45e938517eSTobias Grosser extern "C" { 46a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 47a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 48a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 49a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 50a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 51e938517eSTobias Grosser } 52e938517eSTobias Grosser 539dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 549dfe4e7cSTobias Grosser 559dfe4e7cSTobias Grosser using namespace polly; 569dfe4e7cSTobias Grosser using namespace llvm; 579dfe4e7cSTobias Grosser 589dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 599dfe4e7cSTobias Grosser 60f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 61f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 62681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 63f384594dSTobias Grosser cl::cat(PollyCategory)); 6469b46751STobias Grosser 6569b46751STobias Grosser static cl::opt<bool> 6669b46751STobias Grosser DumpCode("polly-acc-dump-code", 6769b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6869b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6969b46751STobias Grosser 7032837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 7132837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 7232837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7332837fe3STobias Grosser cl::cat(PollyCategory)); 7432837fe3STobias Grosser 7574dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7674dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7774dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7874dc3cb4STobias Grosser cl::cat(PollyCategory)); 7974dc3cb4STobias Grosser 8074dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 8174dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 8274dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8374dc3cb4STobias Grosser cl::cat(PollyCategory)); 84b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 85b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 86b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 87b513b491STobias Grosser cl::cat(PollyCategory)); 88130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 89130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 90130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 91130ca30fSTobias Grosser cl::cat(PollyCategory)); 9274dc3cb4STobias Grosser 93c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory; 94c4a4af47SSiddharth Bhat static cl::opt<bool, true> 95c4a4af47SSiddharth Bhat XManagedMemory("polly-acc-codegen-managed-memory", 96abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 97abed4969SSiddharth Bhat " that all memory has been" 98abed4969SSiddharth Bhat " declared as managed memory"), 99c4a4af47SSiddharth Bhat cl::location(PollyManagedMemory), cl::Hidden, 100c4a4af47SSiddharth Bhat cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 101abed4969SSiddharth Bhat 10265d7f72fSSiddharth Bhat static cl::opt<bool> 10365d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 10465d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10565d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10665d7f72fSSiddharth Bhat " kernel module."), 10765d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10865d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 10965d7f72fSSiddharth Bhat 1108fc6cdfbSTobias Grosser static cl::opt<std::string> CUDALibDevice( 1118fc6cdfbSTobias Grosser "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden, 1128fc6cdfbSTobias Grosser cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"), 1138fc6cdfbSTobias Grosser cl::ZeroOrMore, cl::cat(PollyCategory)); 1148fc6cdfbSTobias Grosser 11574dc3cb4STobias Grosser static cl::opt<std::string> 11674dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 11774dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 11874dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 11974dc3cb4STobias Grosser 12082f2af35STobias Grosser static cl::opt<int> 12182f2af35STobias Grosser MinCompute("polly-acc-mincompute", 12282f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 12382f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 12482f2af35STobias Grosser 125638316daSSiddharth Bhat /// Return a unique name for a Scop, which is the scop region with the 126638316daSSiddharth Bhat /// function name. 127638316daSSiddharth Bhat std::string getUniqueScopName(const Scop *S) { 128638316daSSiddharth Bhat return "Scop Region: " + S->getNameStr() + 129638316daSSiddharth Bhat " | Function: " + std::string(S->getFunction().getName()); 130638316daSSiddharth Bhat } 131638316daSSiddharth Bhat 132a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 133a82f2d26SSiddharth Bhat /// used by live range reordering. 134a82f2d26SSiddharth Bhat /// 135a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 136a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 137a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 138a82f2d26SSiddharth Bhat struct MustKillsInfo { 139a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 140a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 141a82f2d26SSiddharth Bhat /// 142a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 143a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 144a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 145a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 146a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 147a82f2d26SSiddharth Bhat /// killed. 148a82f2d26SSiddharth Bhat /// 149edfef5aeSSiddharth Bhat /// We currently derive kill information for: 150edfef5aeSSiddharth Bhat /// 1. phi nodes. PHI nodes are not alive outside the scop and can 151edfef5aeSSiddharth Bhat /// consequently all be killed. 152edfef5aeSSiddharth Bhat /// 2. Scalar arrays that are not used outside the Scop. This is 153edfef5aeSSiddharth Bhat /// checked by `isScalarUsesContainedInScop`. 154edfef5aeSSiddharth Bhat /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 155a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 156a82f2d26SSiddharth Bhat 1579e3db2b7SSiddharth Bhat /// Tagged must kills stripped of the tags. 1589e3db2b7SSiddharth Bhat /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 1599e3db2b7SSiddharth Bhat isl::union_map MustKills; 1609e3db2b7SSiddharth Bhat 1619e3db2b7SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr) {} 162a82f2d26SSiddharth Bhat }; 163a82f2d26SSiddharth Bhat 164761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 165761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 166761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 167761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 168761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 169761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 170761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 171761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 172761e5b93SSiddharth Bhat 173761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 174761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 175761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 176761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 177761e5b93SSiddharth Bhat if (!R.contains(I)) 178761e5b93SSiddharth Bhat return false; 179761e5b93SSiddharth Bhat } 180761e5b93SSiddharth Bhat return true; 181761e5b93SSiddharth Bhat } 182761e5b93SSiddharth Bhat 183a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 184a82f2d26SSiddharth Bhat /// 185a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 186a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 187a82f2d26SSiddharth Bhat /// PPCG. 188a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 189b65ccc43STobias Grosser const isl::space ParamSpace = S.getParamSpace(); 190a82f2d26SSiddharth Bhat MustKillsInfo Info; 191a82f2d26SSiddharth Bhat 192761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 193761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 194761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 195a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 196a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 197761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 198761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 19977eef90fSTobias Grosser KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 200a82f2d26SSiddharth Bhat } 201a82f2d26SSiddharth Bhat 202d70ea7feSTobias Grosser Info.TaggedMustKills = isl::union_map::empty(ParamSpace); 203d70ea7feSTobias Grosser Info.MustKills = isl::union_map::empty(ParamSpace); 204a82f2d26SSiddharth Bhat 205a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 206a82f2d26SSiddharth Bhat // schedule: 207a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 208a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 209a82f2d26SSiddharth Bhat // at the cost of some code complexity. 210a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 211a82f2d26SSiddharth Bhat 212edfef5aeSSiddharth Bhat for (isl::id &ToKillId : KillMemIds) { 213a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 214edfef5aeSSiddharth Bhat S.getIslCtx(), 215edfef5aeSSiddharth Bhat std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 216a82f2d26SSiddharth Bhat 217a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 218a82f2d26SSiddharth Bhat // 2. We need to construct a map: 219edfef5aeSSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 220a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 221edfef5aeSSiddharth Bhat // 2a. StmtToScalar: 222edfef5aeSSiddharth Bhat // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 223edfef5aeSSiddharth Bhat // 2b. PhantomRefToScalar: 224edfef5aeSSiddharth Bhat // [param] -> { ref_phantom[] -> scalar_to_kill[] } 225a82f2d26SSiddharth Bhat // 226a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 227a82f2d26SSiddharth Bhat // TaggedMustKill: 228edfef5aeSSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 229a82f2d26SSiddharth Bhat 230edfef5aeSSiddharth Bhat // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 231d70ea7feSTobias Grosser isl::map StmtToScalar = isl::map::universe(ParamSpace); 232edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 233edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 234a82f2d26SSiddharth Bhat 235a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 236edfef5aeSSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 237edfef5aeSSiddharth Bhat nullptr); 238a82f2d26SSiddharth Bhat 239edfef5aeSSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 240d70ea7feSTobias Grosser isl::map PhantomRefToScalar = isl::map::universe(ParamSpace); 241edfef5aeSSiddharth Bhat PhantomRefToScalar = 242edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 243edfef5aeSSiddharth Bhat PhantomRefToScalar = 244edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 245a82f2d26SSiddharth Bhat 246edfef5aeSSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 247edfef5aeSSiddharth Bhat isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 248a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 249a82f2d26SSiddharth Bhat 2509e3db2b7SSiddharth Bhat // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 2519e3db2b7SSiddharth Bhat Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 2529e3db2b7SSiddharth Bhat 253a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 254a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 255a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 256a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 257a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 258a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 259a82f2d26SSiddharth Bhat 260a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 261a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 262a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 263a82f2d26SSiddharth Bhat else 264a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 265a82f2d26SSiddharth Bhat } 266a82f2d26SSiddharth Bhat 267a82f2d26SSiddharth Bhat return Info; 268a82f2d26SSiddharth Bhat } 269a82f2d26SSiddharth Bhat 27060c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 27160c60025STobias Grosser /// 27260c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 27360c60025STobias Grosser /// of the scheduled ScopStmts. 27460c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 27535de9009SSiddharth Bhat void *StmtT, __isl_take isl_ast_build *Build_C, 27660c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 27760c60025STobias Grosser isl_id *Id, void *User), 27860c60025STobias Grosser void *UserIndex, 27960c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 280edb885cbSTobias Grosser void *UserExpr) { 28160c60025STobias Grosser 282edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 28360c60025STobias Grosser 28435de9009SSiddharth Bhat if (!Stmt || !Build_C) 285edb885cbSTobias Grosser return NULL; 286edb885cbSTobias Grosser 28735de9009SSiddharth Bhat isl::ast_build Build = isl::manage(isl_ast_build_copy(Build_C)); 28835de9009SSiddharth Bhat isl::ctx Ctx = Build.get_ctx(); 28935de9009SSiddharth Bhat isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0); 290edb885cbSTobias Grosser 291cff9696eSTobias Grosser Stmt->setAstBuild(Build); 292cff9696eSTobias Grosser 293edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 29435de9009SSiddharth Bhat isl::map AddrFunc = Acc->getAddressFunction(); 295dcf8d696STobias Grosser AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain()); 29635de9009SSiddharth Bhat 29735de9009SSiddharth Bhat isl::id RefId = Acc->getId(); 29835de9009SSiddharth Bhat isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 29935de9009SSiddharth Bhat 30035de9009SSiddharth Bhat isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 30135de9009SSiddharth Bhat MPA = MPA.coalesce(); 30235de9009SSiddharth Bhat MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 30335de9009SSiddharth Bhat 30435de9009SSiddharth Bhat isl::ast_expr Access = Build.access_from(MPA); 30535de9009SSiddharth Bhat Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 30635de9009SSiddharth Bhat RefToExpr = RefToExpr.set(RefId, Access); 307edb885cbSTobias Grosser } 308edb885cbSTobias Grosser 30935de9009SSiddharth Bhat return RefToExpr.release(); 31060c60025STobias Grosser } 311f384594dSTobias Grosser 312a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 313a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 314a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 315a90be207SSiddharth Bhat if (bytes == 0) 316a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 317a90be207SSiddharth Bhat return bytes; 318a90be207SSiddharth Bhat } 319a90be207SSiddharth Bhat 32038fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 32138fc0aedSTobias Grosser /// 32238fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 323a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 32438fc0aedSTobias Grosser /// for generating GPU specific user nodes. 32538fc0aedSTobias Grosser /// 32638fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 32738fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 32838fc0aedSTobias Grosser public: 3292d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 33038fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 331acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 33217f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3332d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 33417f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 335edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 336edb885cbSTobias Grosser } 33738fc0aedSTobias Grosser 338fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 339fa7b0802STobias Grosser void initializeAfterRTH(); 340fa7b0802STobias Grosser 341fa7b0802STobias Grosser /// Finalize the generated scop. 342fa7b0802STobias Grosser virtual void finalize(); 343fa7b0802STobias Grosser 3445857b701STobias Grosser /// Track if the full build process was successful. 3455857b701STobias Grosser /// 3465857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3475857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3485857b701STobias Grosser bool BuildSuccessful = true; 3495857b701STobias Grosser 350bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 351bc653f20STobias Grosser unsigned DeepestSequential = 0; 352bc653f20STobias Grosser 353bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 354bc653f20STobias Grosser unsigned DeepestParallel = 0; 355bc653f20STobias Grosser 35679f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 35779f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 35879f13b9aSSingapuram Sanjay Srivallabh 35938fc0aedSTobias Grosser private: 36074dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 36174dc3cb4STobias Grosser /// 36274dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 36374dc3cb4STobias Grosser /// more. 36474dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 36574dc3cb4STobias Grosser 36613c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 36713c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3687287aeddSTobias Grosser 369fa7b0802STobias Grosser /// The current GPU context. 370fa7b0802STobias Grosser Value *GPUContext; 371fa7b0802STobias Grosser 372b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 373b513b491STobias Grosser std::vector<isl_id *> KernelIds; 374b513b491STobias Grosser 37532837fe3STobias Grosser /// A module containing GPU code. 37632837fe3STobias Grosser /// 37732837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 37832837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 37932837fe3STobias Grosser 38032837fe3STobias Grosser /// The GPU program we generate code for. 38132837fe3STobias Grosser gpu_prog *Prog; 38232837fe3STobias Grosser 38317f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 38417f01968SSiddharth Bhat GPURuntime Runtime; 38517f01968SSiddharth Bhat 38617f01968SSiddharth Bhat /// The GPU Architecture to target. 38717f01968SSiddharth Bhat GPUArch Arch; 38817f01968SSiddharth Bhat 389472f9654STobias Grosser /// Class to free isl_ids. 390472f9654STobias Grosser class IslIdDeleter { 391472f9654STobias Grosser public: 392472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 393472f9654STobias Grosser }; 394472f9654STobias Grosser 395472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 396472f9654STobias Grosser /// 397472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 398472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 399472f9654STobias Grosser 400edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 401edb885cbSTobias Grosser 40238fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 40338fc0aedSTobias Grosser /// 40438fc0aedSTobias Grosser /// These AST nodes can be of type: 40538fc0aedSTobias Grosser /// 40638fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 40738fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 40813c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 4095260c041STobias Grosser /// - In-kernel synchronization 4105260c041STobias Grosser /// - In-kernel memory copy statement 41138fc0aedSTobias Grosser /// 4121fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 4131fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 41432837fe3STobias Grosser 41513c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 41613c78e4dSTobias Grosser 41713c78e4dSTobias Grosser /// Create code for a data transfer statement 41813c78e4dSTobias Grosser /// 41913c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 42013c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 42113c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 42213c78e4dSTobias Grosser enum DataDirection Direction); 42313c78e4dSTobias Grosser 424edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 425edb885cbSTobias Grosser /// 426edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 427edb885cbSTobias Grosser /// 428e53c924bSSiddharth Bhat /// @returns A tuple, whose: 429e53c924bSSiddharth Bhat /// - First element contains the set of values referenced by the 430e53c924bSSiddharth Bhat /// kernel 431e53c924bSSiddharth Bhat /// - Second element contains the set of functions referenced by the 432e53c924bSSiddharth Bhat /// kernel. All functions in the set satisfy 433e53c924bSSiddharth Bhat /// `isValidFunctionInKernel`. 434e53c924bSSiddharth Bhat /// - Third element contains loops that have induction variables 435e53c924bSSiddharth Bhat /// which are used in the kernel, *and* these loops are *neither* 436e53c924bSSiddharth Bhat /// in the scop, nor do they immediately surroung the Scop. 437e53c924bSSiddharth Bhat /// See [Code generation of induction variables of loops outside 438e53c924bSSiddharth Bhat /// Scops] 439*43df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 440*43df2020STobias Grosser isl::space> 441f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 442edb885cbSTobias Grosser 44379a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 44479a947c2STobias Grosser /// 44579a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 44679a947c2STobias Grosser /// 44779a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 44879a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 44979a947c2STobias Grosser 450b99c1171STobias Grosser /// Get the managed array pointer for sending host pointers to the device. 451abed4969SSiddharth Bhat /// \note 452abed4969SSiddharth Bhat /// This is to be used only with managed memory 453b99c1171STobias Grosser Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo); 454abed4969SSiddharth Bhat 45579a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 45679a947c2STobias Grosser /// 45779a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 45879a947c2STobias Grosser /// 45979a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 46079a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 46179a947c2STobias Grosser 462a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 463a90be207SSiddharth Bhat /// parameters. 464a90be207SSiddharth Bhat /// 465a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 466a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 467a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 468a90be207SSiddharth Bhat /// parameter. 469a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 470a90be207SSiddharth Bhat int Index); 471a90be207SSiddharth Bhat 47279a947c2STobias Grosser /// Create kernel launch parameters. 47379a947c2STobias Grosser /// 47479a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 47579a947c2STobias Grosser /// @param F The kernel function that has been created. 47657693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 47779a947c2STobias Grosser /// 47879a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 47979a947c2STobias Grosser /// values that are passed to the kernel. 48057693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 48157693272STobias Grosser SetVector<Value *> SubtreeValues); 48279a947c2STobias Grosser 483b513b491STobias Grosser /// Create declarations for kernel variable. 484b513b491STobias Grosser /// 485b513b491STobias Grosser /// This includes shared memory declarations. 486b513b491STobias Grosser /// 487b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 488b513b491STobias Grosser /// @param FN The function into which to generate the variables. 489b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 490b513b491STobias Grosser 491c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 492c1c6a2a6STobias Grosser /// 493c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 494c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 495c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 496c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 497c1c6a2a6STobias Grosser /// as specified here. 498c1c6a2a6STobias Grosser /// 499c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 500c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 501c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 502c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 503c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 504c1c6a2a6STobias Grosser Value *BlockDimZ); 505c1c6a2a6STobias Grosser 50632837fe3STobias Grosser /// Create GPU kernel. 50732837fe3STobias Grosser /// 50832837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 50932837fe3STobias Grosser /// 51032837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 51132837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 51232837fe3STobias Grosser 51313c78e4dSTobias Grosser /// Generate code that computes the size of an array. 51413c78e4dSTobias Grosser /// 51513c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 51613c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 51713c78e4dSTobias Grosser 518aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 519aaabbbf8STobias Grosser /// 520aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 521aaabbbf8STobias Grosser /// 522aaabbbf8STobias Grosser /// Example: 523aaabbbf8STobias Grosser /// 524aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 525aaabbbf8STobias Grosser /// A[i + 42] += ... 526aaabbbf8STobias Grosser /// 527aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 528aaabbbf8STobias Grosser /// 529aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 530aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 531aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 532aaabbbf8STobias Grosser 53300bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 53400bb5a99STobias Grosser /// 53500bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 53600bb5a99STobias Grosser /// @param FN The function created for the kernel. 53700bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 53800bb5a99STobias Grosser 53932837fe3STobias Grosser /// Create kernel function. 54032837fe3STobias Grosser /// 54132837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 54232837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 54332837fe3STobias Grosser /// start block of this newly created function. 54432837fe3STobias Grosser /// 54532837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 546edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 547f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 548f291c8d5SSiddharth Bhat /// kernel. 549edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 550f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 551f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 55232837fe3STobias Grosser 55332837fe3STobias Grosser /// Create the declaration of a kernel function. 55432837fe3STobias Grosser /// 55532837fe3STobias Grosser /// The kernel function takes as arguments: 55632837fe3STobias Grosser /// 55732837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 558f6044bd0STobias Grosser /// - Host iterators 559c84a1995STobias Grosser /// - Parameters 56032837fe3STobias Grosser /// - Other LLVM Value references (TODO) 56132837fe3STobias Grosser /// 56232837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 563edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 564edb885cbSTobias Grosser /// 56532837fe3STobias Grosser /// @returns The newly declared function. 566edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 567edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 56832837fe3STobias Grosser 569472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 570472f9654STobias Grosser /// 571472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 572472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 573472f9654STobias Grosser 5742f3073b5SPhilipp Schaad /// Insert function calls to retrieve the SPIR group/local ids. 5752f3073b5SPhilipp Schaad /// 5762f3073b5SPhilipp Schaad /// @param The kernel to generate the function calls for. 5772f3073b5SPhilipp Schaad void insertKernelCallsSPIR(ppcg_kernel *Kernel); 5782f3073b5SPhilipp Schaad 579f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 580f291c8d5SSiddharth Bhat /// 581f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 582f291c8d5SSiddharth Bhat /// SubtreeFunctions. 583f291c8d5SSiddharth Bhat /// 584f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 585f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 586f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 587f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 588f291c8d5SSiddharth Bhat /// 589f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 590f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 591f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 592f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 593f291c8d5SSiddharth Bhat /// 594f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 595f291c8d5SSiddharth Bhat /// this kernel. 596f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 597f291c8d5SSiddharth Bhat 598b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 599b513b491STobias Grosser /// 600b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 601b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 602b513b491STobias Grosser 603edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 604edb885cbSTobias Grosser /// 605edb885cbSTobias Grosser /// @param Expr The expression containing the call. 606edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 607edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 608edb885cbSTobias Grosser 6095260c041STobias Grosser /// Create an in-kernel synchronization call. 6105260c041STobias Grosser void createKernelSync(); 6115260c041STobias Grosser 61274dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 61374dc3cb4STobias Grosser /// 61474dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 61574dc3cb4STobias Grosser std::string createKernelASM(); 61674dc3cb4STobias Grosser 61774dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 61874dc3cb4STobias Grosser /// 61974dc3cb4STobias Grosser /// @param F The function to remove references to. 62074dc3cb4STobias Grosser void clearDominators(Function *F); 62174dc3cb4STobias Grosser 62274dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 62374dc3cb4STobias Grosser /// 62474dc3cb4STobias Grosser /// @param F The function to remove references to. 62574dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 62674dc3cb4STobias Grosser 62774dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 62874dc3cb4STobias Grosser /// 62974dc3cb4STobias Grosser /// @param F The function to remove references to. 63074dc3cb4STobias Grosser void clearLoops(Function *F); 63174dc3cb4STobias Grosser 6328fc6cdfbSTobias Grosser /// Check if the scop requires to be linked with CUDA's libdevice. 6338fc6cdfbSTobias Grosser bool requiresCUDALibDevice(); 6348fc6cdfbSTobias Grosser 6358fc6cdfbSTobias Grosser /// Link with the NVIDIA libdevice library (if needed and available). 6368fc6cdfbSTobias Grosser void addCUDALibDevice(); 6378fc6cdfbSTobias Grosser 63832837fe3STobias Grosser /// Finalize the generation of the kernel function. 63932837fe3STobias Grosser /// 64032837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 64132837fe3STobias Grosser /// dump its IR to stderr. 64257793596STobias Grosser /// 64357793596STobias Grosser /// @returns The Assembly string of the kernel. 64457793596STobias Grosser std::string finalizeKernelFunction(); 645fa7b0802STobias Grosser 64651dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 64751dfc275STobias Grosser /// 64851dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 649a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 65051dfc275STobias Grosser /// the kernel terminates. 65151dfc275STobias Grosser /// 65251dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 65351dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 65451dfc275STobias Grosser 6557287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 656fa7b0802STobias Grosser void allocateDeviceArrays(); 657fa7b0802STobias Grosser 658b99c1171STobias Grosser /// Create code to prepare the managed device pointers. 659b99c1171STobias Grosser void prepareManagedDeviceArrays(); 660b99c1171STobias Grosser 6617287aeddSTobias Grosser /// Free all allocated device arrays. 6627287aeddSTobias Grosser void freeDeviceArrays(); 6637287aeddSTobias Grosser 664fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 665fa7b0802STobias Grosser /// 666fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 667fa7b0802STobias Grosser Value *createCallInitContext(); 668fa7b0802STobias Grosser 66979a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 67079a947c2STobias Grosser /// 67179a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 67279a947c2STobias Grosser /// 67379a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 67479a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 67579a947c2STobias Grosser 676fa7b0802STobias Grosser /// Create a call to free the GPU context. 677fa7b0802STobias Grosser /// 678fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 679fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 680fa7b0802STobias Grosser 6817287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6827287aeddSTobias Grosser /// 6837287aeddSTobias Grosser /// @param Size The size of memory to allocate 6847287aeddSTobias Grosser /// 6857287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 686fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6877287aeddSTobias Grosser 6887287aeddSTobias Grosser /// Create a call to free a device array. 6897287aeddSTobias Grosser /// 6907287aeddSTobias Grosser /// @param Array The device array to free. 6917287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 69213c78e4dSTobias Grosser 69313c78e4dSTobias Grosser /// Create a call to copy data from host to device. 69413c78e4dSTobias Grosser /// 69513c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 69613c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 69713c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 69813c78e4dSTobias Grosser Value *Size); 69913c78e4dSTobias Grosser 70013c78e4dSTobias Grosser /// Create a call to copy data from device to host. 70113c78e4dSTobias Grosser /// 70213c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 70313c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 70413c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 70513c78e4dSTobias Grosser Value *Size); 70657793596STobias Grosser 707abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 708abed4969SSiddharth Bhat /// \note 709abed4969SSiddharth Bhat /// This is to be used only with managed memory. 710abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 711abed4969SSiddharth Bhat 71257793596STobias Grosser /// Create a call to get a kernel from an assembly string. 71357793596STobias Grosser /// 71457793596STobias Grosser /// @param Buffer The string describing the kernel. 71557793596STobias Grosser /// @param Entry The name of the kernel function to call. 71657793596STobias Grosser /// 71757793596STobias Grosser /// @returns A pointer to a kernel object 71857793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 71957793596STobias Grosser 72057793596STobias Grosser /// Create a call to free a GPU kernel. 72157793596STobias Grosser /// 72257793596STobias Grosser /// @param GPUKernel THe kernel to free. 72357793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 72479a947c2STobias Grosser 72579a947c2STobias Grosser /// Create a call to launch a GPU kernel. 72679a947c2STobias Grosser /// 72779a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 72879a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 72979a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 73079a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 73179a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 73279a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 733a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 73479a947c2STobias Grosser /// the parameter values passed for each kernel argument. 73579a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 73679a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 73779a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 73879a947c2STobias Grosser Value *Parameters); 7391fb9b64dSTobias Grosser }; 7401fb9b64dSTobias Grosser 74179f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 7421abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 7431abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 74479f13b9aSSingapuram Sanjay Srivallabh } 74579f13b9aSSingapuram Sanjay Srivallabh 746fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 747750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 748750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 749750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 750750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 751750160e2STobias Grosser 752fa7b0802STobias Grosser GPUContext = createCallInitContext(); 753abed4969SSiddharth Bhat 754c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 755fa7b0802STobias Grosser allocateDeviceArrays(); 756b99c1171STobias Grosser else 757b99c1171STobias Grosser prepareManagedDeviceArrays(); 758fa7b0802STobias Grosser } 759fa7b0802STobias Grosser 760fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 761c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 7627287aeddSTobias Grosser freeDeviceArrays(); 763abed4969SSiddharth Bhat 764fa7b0802STobias Grosser createCallFreeContext(GPUContext); 765fa7b0802STobias Grosser IslNodeBuilder::finalize(); 766fa7b0802STobias Grosser } 767fa7b0802STobias Grosser 768fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 769c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 770c4a4af47SSiddharth Bhat "Managed memory will directly send host pointers " 771abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 7728ea1fc19STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release()); 773fa7b0802STobias Grosser 774fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 775fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 77613c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7777287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7787287aeddSTobias Grosser DevArrayName.append(Array->name); 779fa7b0802STobias Grosser 78013c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 781aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 782aaabbbf8STobias Grosser if (Offset) 783aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 784aaabbbf8STobias Grosser ArraySize, 785aaabbbf8STobias Grosser Builder.CreateMul(Offset, 786aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 78734eeabbcSSiddharth Bhat const SCEV *SizeSCEV = SE.getSCEV(ArraySize); 78834eeabbcSSiddharth Bhat // It makes no sense to have an array of size 0. The CUDA API will 78934eeabbcSSiddharth Bhat // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We 79034eeabbcSSiddharth Bhat // choose to be defensive and catch this at the compile phase. It is 79134eeabbcSSiddharth Bhat // most likely that we are doing something wrong with size computation. 79234eeabbcSSiddharth Bhat if (SizeSCEV->isZero()) { 79334eeabbcSSiddharth Bhat errs() << getUniqueScopName(&S) 79434eeabbcSSiddharth Bhat << " has computed array size 0: " << *ArraySize 79534eeabbcSSiddharth Bhat << " | for array: " << *(ScopArray->getBasePtr()) 79634eeabbcSSiddharth Bhat << ". This is illegal, exiting.\n"; 79734eeabbcSSiddharth Bhat report_fatal_error("array size was computed to be 0"); 79834eeabbcSSiddharth Bhat } 79934eeabbcSSiddharth Bhat 8007287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 8017287aeddSTobias Grosser DevArray->setName(DevArrayName); 80213c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 803fa7b0802STobias Grosser } 804fa7b0802STobias Grosser 805fa7b0802STobias Grosser isl_ast_build_free(Build); 806fa7b0802STobias Grosser } 807fa7b0802STobias Grosser 808b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() { 809c4a4af47SSiddharth Bhat assert(PollyManagedMemory && 810b99c1171STobias Grosser "Device array most only be prepared in managed-memory mode"); 811b99c1171STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 812b99c1171STobias Grosser gpu_array_info *Array = &Prog->array[i]; 813b99c1171STobias Grosser ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user; 814b99c1171STobias Grosser Value *HostPtr; 815b99c1171STobias Grosser 816b99c1171STobias Grosser if (gpu_array_is_scalar(Array)) 817b99c1171STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 818b99c1171STobias Grosser else 819b99c1171STobias Grosser HostPtr = ScopArray->getBasePtr(); 820b99c1171STobias Grosser HostPtr = getLatestValue(HostPtr); 821b99c1171STobias Grosser 822b99c1171STobias Grosser Value *Offset = getArrayOffset(Array); 823b99c1171STobias Grosser if (Offset) { 824b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast( 825b99c1171STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 826b99c1171STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 827b99c1171STobias Grosser } 828b99c1171STobias Grosser 829b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 830b99c1171STobias Grosser DeviceAllocations[ScopArray] = HostPtr; 831b99c1171STobias Grosser } 832b99c1171STobias Grosser } 833b99c1171STobias Grosser 834c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 835c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 836c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 837c1c6a2a6STobias Grosser 838c1c6a2a6STobias Grosser for (auto &F : *M) { 839c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 840c1c6a2a6STobias Grosser continue; 841c1c6a2a6STobias Grosser 842c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 843c1c6a2a6STobias Grosser 844c1c6a2a6STobias Grosser Metadata *Elements[] = { 845c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 846c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 847c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 848c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 849c1c6a2a6STobias Grosser }; 850c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 851c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 852c1c6a2a6STobias Grosser } 853c1c6a2a6STobias Grosser } 854c1c6a2a6STobias Grosser 8557287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 856c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory does not use device arrays"); 85713c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 85813c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 8597287aeddSTobias Grosser } 8607287aeddSTobias Grosser 86157793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 86257793596STobias Grosser const char *Name = "polly_getKernel"; 86357793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 86457793596STobias Grosser Function *F = M->getFunction(Name); 86557793596STobias Grosser 86657793596STobias Grosser // If F is not available, declare it. 86757793596STobias Grosser if (!F) { 86857793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 86957793596STobias Grosser std::vector<Type *> Args; 87057793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87157793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 87257793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 87357793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 87457793596STobias Grosser } 87557793596STobias Grosser 87657793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 87757793596STobias Grosser } 87857793596STobias Grosser 87979a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 88079a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 88179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 88279a947c2STobias Grosser Function *F = M->getFunction(Name); 88379a947c2STobias Grosser 88479a947c2STobias Grosser // If F is not available, declare it. 88579a947c2STobias Grosser if (!F) { 88679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 88779a947c2STobias Grosser std::vector<Type *> Args; 88879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 88979a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 89079a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 89179a947c2STobias Grosser } 89279a947c2STobias Grosser 89379a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 89479a947c2STobias Grosser } 89579a947c2STobias Grosser 89679a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 89779a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 89879a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 89979a947c2STobias Grosser Value *Parameters) { 90079a947c2STobias Grosser const char *Name = "polly_launchKernel"; 90179a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 90279a947c2STobias Grosser Function *F = M->getFunction(Name); 90379a947c2STobias Grosser 90479a947c2STobias Grosser // If F is not available, declare it. 90579a947c2STobias Grosser if (!F) { 90679a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 90779a947c2STobias Grosser std::vector<Type *> Args; 90879a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91079a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91179a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91279a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91379a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91479a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91579a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 91679a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 91779a947c2STobias Grosser } 91879a947c2STobias Grosser 919ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 92079a947c2STobias Grosser BlockDimZ, Parameters}); 92179a947c2STobias Grosser } 92279a947c2STobias Grosser 92357793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 92457793596STobias Grosser const char *Name = "polly_freeKernel"; 92557793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 92657793596STobias Grosser Function *F = M->getFunction(Name); 92757793596STobias Grosser 92857793596STobias Grosser // If F is not available, declare it. 92957793596STobias Grosser if (!F) { 93057793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 93157793596STobias Grosser std::vector<Type *> Args; 93257793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93357793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 93457793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 93557793596STobias Grosser } 93657793596STobias Grosser 93757793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 93857793596STobias Grosser } 93957793596STobias Grosser 9407287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 941c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 942c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 943abed4969SSiddharth Bhat "for device"); 9447287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 9457287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9467287aeddSTobias Grosser Function *F = M->getFunction(Name); 9477287aeddSTobias Grosser 9487287aeddSTobias Grosser // If F is not available, declare it. 9497287aeddSTobias Grosser if (!F) { 9507287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 9517287aeddSTobias Grosser std::vector<Type *> Args; 9527287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 9537287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 9547287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 9557287aeddSTobias Grosser } 9567287aeddSTobias Grosser 9577287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 9587287aeddSTobias Grosser } 9597287aeddSTobias Grosser 960fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 961c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 962c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 963abed4969SSiddharth Bhat "for device"); 964fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 965fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 966fa7b0802STobias Grosser Function *F = M->getFunction(Name); 967fa7b0802STobias Grosser 968fa7b0802STobias Grosser // If F is not available, declare it. 969fa7b0802STobias Grosser if (!F) { 970fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 971fa7b0802STobias Grosser std::vector<Type *> Args; 972fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 973fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 974fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 975fa7b0802STobias Grosser } 976fa7b0802STobias Grosser 977fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 978fa7b0802STobias Grosser } 979fa7b0802STobias Grosser 98013c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 98113c78e4dSTobias Grosser Value *DeviceData, 98213c78e4dSTobias Grosser Value *Size) { 983c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 984c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 985abed4969SSiddharth Bhat "device and host"); 98613c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 98713c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 98813c78e4dSTobias Grosser Function *F = M->getFunction(Name); 98913c78e4dSTobias Grosser 99013c78e4dSTobias Grosser // If F is not available, declare it. 99113c78e4dSTobias Grosser if (!F) { 99213c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 99313c78e4dSTobias Grosser std::vector<Type *> Args; 99413c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99613c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 99713c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 99813c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 99913c78e4dSTobias Grosser } 100013c78e4dSTobias Grosser 100113c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 100213c78e4dSTobias Grosser } 100313c78e4dSTobias Grosser 100413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 100513c78e4dSTobias Grosser Value *HostData, 100613c78e4dSTobias Grosser Value *Size) { 1007c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 1008c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 1009abed4969SSiddharth Bhat "device and host"); 101013c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 101113c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 101213c78e4dSTobias Grosser Function *F = M->getFunction(Name); 101313c78e4dSTobias Grosser 101413c78e4dSTobias Grosser // If F is not available, declare it. 101513c78e4dSTobias Grosser if (!F) { 101613c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 101713c78e4dSTobias Grosser std::vector<Type *> Args; 101813c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 101913c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 102013c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 102113c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 102213c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 102313c78e4dSTobias Grosser } 102413c78e4dSTobias Grosser 102513c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 102613c78e4dSTobias Grosser } 102713c78e4dSTobias Grosser 1028abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 1029c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "explicit synchronization is only necessary for " 1030abed4969SSiddharth Bhat "managed memory"); 1031abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 1032abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1033abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 1034abed4969SSiddharth Bhat 1035abed4969SSiddharth Bhat // If F is not available, declare it. 1036abed4969SSiddharth Bhat if (!F) { 1037abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1038abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 1039abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 1040abed4969SSiddharth Bhat } 1041abed4969SSiddharth Bhat 1042abed4969SSiddharth Bhat Builder.CreateCall(F); 1043abed4969SSiddharth Bhat } 1044abed4969SSiddharth Bhat 1045fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 104617f01968SSiddharth Bhat const char *Name; 104717f01968SSiddharth Bhat 104817f01968SSiddharth Bhat switch (Runtime) { 104917f01968SSiddharth Bhat case GPURuntime::CUDA: 105017f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 105117f01968SSiddharth Bhat break; 105217f01968SSiddharth Bhat case GPURuntime::OpenCL: 105317f01968SSiddharth Bhat Name = "polly_initContextCL"; 105417f01968SSiddharth Bhat break; 105517f01968SSiddharth Bhat } 105617f01968SSiddharth Bhat 1057fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1058fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1059fa7b0802STobias Grosser 1060fa7b0802STobias Grosser // If F is not available, declare it. 1061fa7b0802STobias Grosser if (!F) { 1062fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1063fa7b0802STobias Grosser std::vector<Type *> Args; 1064fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1065fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1066fa7b0802STobias Grosser } 1067fa7b0802STobias Grosser 1068fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 1069fa7b0802STobias Grosser } 1070fa7b0802STobias Grosser 1071fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 1072fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 1073fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1074fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1075fa7b0802STobias Grosser 1076fa7b0802STobias Grosser // If F is not available, declare it. 1077fa7b0802STobias Grosser if (!F) { 1078fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1079fa7b0802STobias Grosser std::vector<Type *> Args; 1080fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 1081fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1082fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1083fa7b0802STobias Grosser } 1084fa7b0802STobias Grosser 1085fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 1086fa7b0802STobias Grosser } 1087fa7b0802STobias Grosser 10885260c041STobias Grosser /// Check if one string is a prefix of another. 10895260c041STobias Grosser /// 10905260c041STobias Grosser /// @param String The string in which to look for the prefix. 10915260c041STobias Grosser /// @param Prefix The prefix to look for. 10925260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 10935260c041STobias Grosser return String.find(Prefix) == 0; 10945260c041STobias Grosser } 10955260c041STobias Grosser 109613c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1097b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 109813c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 109913c78e4dSTobias Grosser 110013c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 1101f7face4bSSiddharth Bhat isl::multi_pw_aff ArrayBound = 1102f7face4bSSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Array->bound)); 1103f7face4bSSiddharth Bhat 1104f7face4bSSiddharth Bhat isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0); 1105f7face4bSSiddharth Bhat isl::ast_expr Res = Build.expr_from(OffsetDimZero); 110613c78e4dSTobias Grosser 110713c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 1108f7face4bSSiddharth Bhat isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i); 1109f7face4bSSiddharth Bhat isl::ast_expr Expr = Build.expr_from(Bound_I); 1110f7face4bSSiddharth Bhat Res = Res.mul(Expr); 111113c78e4dSTobias Grosser } 111213c78e4dSTobias Grosser 1113f7face4bSSiddharth Bhat Value *NumElements = ExprBuilder.create(Res.release()); 1114b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1115b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 111613c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 111713c78e4dSTobias Grosser } 111813c78e4dSTobias Grosser return ArraySize; 111913c78e4dSTobias Grosser } 112013c78e4dSTobias Grosser 1121aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1122aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1123aaabbbf8STobias Grosser return nullptr; 1124aaabbbf8STobias Grosser 1125b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1126aaabbbf8STobias Grosser 1127ccbf4b50SSiddharth Bhat isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin(); 1128aaabbbf8STobias Grosser 1129ccbf4b50SSiddharth Bhat isl::set ZeroSet = isl::set::universe(Min.get_space()); 1130aaabbbf8STobias Grosser 1131ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) 1132ccbf4b50SSiddharth Bhat ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1133aaabbbf8STobias Grosser 1134ccbf4b50SSiddharth Bhat if (Min.is_subset(ZeroSet)) { 1135aaabbbf8STobias Grosser return nullptr; 1136aaabbbf8STobias Grosser } 1137aaabbbf8STobias Grosser 1138ccbf4b50SSiddharth Bhat isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0)); 1139aaabbbf8STobias Grosser 1140ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) { 1141aaabbbf8STobias Grosser if (i > 0) { 1142ccbf4b50SSiddharth Bhat isl::pw_aff Bound_I = 1143ccbf4b50SSiddharth Bhat isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1144ccbf4b50SSiddharth Bhat isl::ast_expr BExpr = Build.expr_from(Bound_I); 1145ccbf4b50SSiddharth Bhat Result = Result.mul(BExpr); 1146aaabbbf8STobias Grosser } 1147ccbf4b50SSiddharth Bhat isl::pw_aff DimMin = Min.dim_min(i); 1148ccbf4b50SSiddharth Bhat isl::ast_expr MExpr = Build.expr_from(DimMin); 1149ccbf4b50SSiddharth Bhat Result = Result.add(MExpr); 1150aaabbbf8STobias Grosser } 1151aaabbbf8STobias Grosser 1152ccbf4b50SSiddharth Bhat return ExprBuilder.create(Result.release()); 1153aaabbbf8STobias Grosser } 1154aaabbbf8STobias Grosser 1155b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1156abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1157c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "Only used when you wish to get a host " 1158abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1159abed4969SSiddharth Bhat "with managed memory"); 1160abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1161b99c1171STobias Grosser it = DeviceAllocations.find(ArrayInfo); 1162b99c1171STobias Grosser assert(it != DeviceAllocations.end() && 1163b99c1171STobias Grosser "Device array expected to be available"); 1164abed4969SSiddharth Bhat return it->second; 1165abed4969SSiddharth Bhat } 1166abed4969SSiddharth Bhat 116713c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 116813c78e4dSTobias Grosser enum DataDirection Direction) { 1169c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory needs no data transfers"); 117013c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 117113c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 117213c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 117313c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 117413c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 117513c78e4dSTobias Grosser 117613c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1177aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 117813c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 117913c78e4dSTobias Grosser 1180b06ff457STobias Grosser Value *HostPtr; 1181b06ff457STobias Grosser 1182b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1183b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1184b06ff457STobias Grosser else 1185b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 1186edf9581eSSiddharth Bhat HostPtr = getLatestValue(HostPtr); 118713c78e4dSTobias Grosser 1188aaabbbf8STobias Grosser if (Offset) { 1189aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1190aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1191aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1192aaabbbf8STobias Grosser } 1193aaabbbf8STobias Grosser 119413c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 119513c78e4dSTobias Grosser 1196aaabbbf8STobias Grosser if (Offset) { 1197aaabbbf8STobias Grosser Size = Builder.CreateSub( 1198ff40087aSTobias Grosser Size, Builder.CreateMul( 1199ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1200aaabbbf8STobias Grosser } 1201aaabbbf8STobias Grosser 120213c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 120313c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 120413c78e4dSTobias Grosser else 120513c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 120613c78e4dSTobias Grosser 120713c78e4dSTobias Grosser isl_id_free(Id); 120813c78e4dSTobias Grosser isl_ast_expr_free(Arg); 120913c78e4dSTobias Grosser isl_ast_expr_free(Expr); 121013c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 121113c78e4dSTobias Grosser } 121213c78e4dSTobias Grosser 12131fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 121432837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 121532837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 121632837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 121732837fe3STobias Grosser isl_id_free(Id); 121832837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 121932837fe3STobias Grosser 122032837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 122132837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 122232837fe3STobias Grosser createKernel(UserStmt); 122362acb344STobias Grosser if (PollyManagedMemory) 122462acb344STobias Grosser createCallSynchronizeDevice(); 122532837fe3STobias Grosser isl_ast_expr_free(Expr); 122632837fe3STobias Grosser return; 122732837fe3STobias Grosser } 12289e3db2b7SSiddharth Bhat if (!strcmp(Str, "init_device")) { 12299e3db2b7SSiddharth Bhat initializeAfterRTH(); 12309e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12319e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12329e3db2b7SSiddharth Bhat return; 12339e3db2b7SSiddharth Bhat } 12349e3db2b7SSiddharth Bhat if (!strcmp(Str, "clear_device")) { 12359e3db2b7SSiddharth Bhat finalize(); 12369e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12379e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12389e3db2b7SSiddharth Bhat return; 12399e3db2b7SSiddharth Bhat } 124013c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1241c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 124213c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1243abed4969SSiddharth Bhat else 1244abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1245abed4969SSiddharth Bhat 124632837fe3STobias Grosser isl_ast_expr_free(Expr); 124713c78e4dSTobias Grosser return; 124813c78e4dSTobias Grosser } 124913c78e4dSTobias Grosser 125013c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1251c4a4af47SSiddharth Bhat if (!PollyManagedMemory) { 125213c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1253abed4969SSiddharth Bhat } else { 1254abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1255abed4969SSiddharth Bhat } 125613c78e4dSTobias Grosser isl_ast_expr_free(Expr); 125738fc0aedSTobias Grosser return; 125838fc0aedSTobias Grosser } 125938fc0aedSTobias Grosser 12605260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 12615260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 12625260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 12635260c041STobias Grosser isl_id_free(Anno); 12645260c041STobias Grosser 12655260c041STobias Grosser switch (KernelStmt->type) { 12665260c041STobias Grosser case ppcg_kernel_domain: 1267edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 12685260c041STobias Grosser isl_ast_node_free(UserStmt); 12695260c041STobias Grosser return; 12705260c041STobias Grosser case ppcg_kernel_copy: 1271b513b491STobias Grosser createKernelCopy(KernelStmt); 12725260c041STobias Grosser isl_ast_expr_free(Expr); 12735260c041STobias Grosser isl_ast_node_free(UserStmt); 12745260c041STobias Grosser return; 12755260c041STobias Grosser case ppcg_kernel_sync: 12765260c041STobias Grosser createKernelSync(); 12775260c041STobias Grosser isl_ast_expr_free(Expr); 12785260c041STobias Grosser isl_ast_node_free(UserStmt); 12795260c041STobias Grosser return; 12805260c041STobias Grosser } 12815260c041STobias Grosser 12825260c041STobias Grosser isl_ast_expr_free(Expr); 12835260c041STobias Grosser isl_ast_node_free(UserStmt); 12845260c041STobias Grosser return; 12855260c041STobias Grosser } 1286b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1287b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1288b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1289b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1290b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1291b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1292b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1293b513b491STobias Grosser 1294b513b491STobias Grosser if (KernelStmt->u.c.read) { 1295b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1296b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1297b513b491STobias Grosser } else { 1298b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1299b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1300b513b491STobias Grosser } 1301b513b491STobias Grosser } 13025260c041STobias Grosser 1303edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1304edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1305edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1306edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1307edb885cbSTobias Grosser 1308edb885cbSTobias Grosser LoopToScevMapT LTS; 1309edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1310edb885cbSTobias Grosser 1311edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1312edb885cbSTobias Grosser 1313edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1314edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1315edb885cbSTobias Grosser else 1316a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1317edb885cbSTobias Grosser } 1318edb885cbSTobias Grosser 13195260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 13205260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13212f3073b5SPhilipp Schaad const char *SpirName = "__gen_ocl_barrier_global"; 132217f01968SSiddharth Bhat 132317f01968SSiddharth Bhat Function *Sync; 132417f01968SSiddharth Bhat 132517f01968SSiddharth Bhat switch (Arch) { 13262f3073b5SPhilipp Schaad case GPUArch::SPIR64: 13272f3073b5SPhilipp Schaad case GPUArch::SPIR32: 13282f3073b5SPhilipp Schaad Sync = M->getFunction(SpirName); 13292f3073b5SPhilipp Schaad 13302f3073b5SPhilipp Schaad // If Sync is not available, declare it. 13312f3073b5SPhilipp Schaad if (!Sync) { 13322f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 13332f3073b5SPhilipp Schaad std::vector<Type *> Args; 13342f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 13352f3073b5SPhilipp Schaad Sync = Function::Create(Ty, Linkage, SpirName, M); 13362f3073b5SPhilipp Schaad Sync->setCallingConv(CallingConv::SPIR_FUNC); 13372f3073b5SPhilipp Schaad } 13382f3073b5SPhilipp Schaad break; 133917f01968SSiddharth Bhat case GPUArch::NVPTX64: 134017f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 134117f01968SSiddharth Bhat break; 134217f01968SSiddharth Bhat } 134317f01968SSiddharth Bhat 13445260c041STobias Grosser Builder.CreateCall(Sync, {}); 13455260c041STobias Grosser } 13465260c041STobias Grosser 1347edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1348edb885cbSTobias Grosser /// 1349edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1350edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1351edb885cbSTobias Grosser /// 1352edb885cbSTobias Grosser /// @param Node The node to collect references for. 1353edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1354edb885cbSTobias Grosser /// 1355edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1356edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1357edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1358edb885cbSTobias Grosser return isl_bool_true; 1359edb885cbSTobias Grosser 1360edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1361edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1362edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1363edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1364edb885cbSTobias Grosser isl_id_free(Id); 1365edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1366edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1367edb885cbSTobias Grosser 1368edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1369edb885cbSTobias Grosser return isl_bool_true; 1370edb885cbSTobias Grosser 1371edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1372edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1373edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1374edb885cbSTobias Grosser isl_id_free(Id); 1375edb885cbSTobias Grosser 137600bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1377edb885cbSTobias Grosser 1378edb885cbSTobias Grosser return isl_bool_true; 1379edb885cbSTobias Grosser } 1380edb885cbSTobias Grosser 13818fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice. 13828fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = { 13838fc6cdfbSTobias Grosser "exp", "expf", "expl", "cos", "cosf", 13848fc6cdfbSTobias Grosser "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"}; 13858fc6cdfbSTobias Grosser 13868fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F. 13878fc6cdfbSTobias Grosser /// 13888fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA. 13898fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) { 13908fc6cdfbSTobias Grosser if (CUDALibDeviceFunctions.count(F->getName())) 13918fc6cdfbSTobias Grosser return std::string("__nv_") + std::string(F->getName()); 13928fc6cdfbSTobias Grosser 13938fc6cdfbSTobias Grosser return ""; 13948fc6cdfbSTobias Grosser } 13958fc6cdfbSTobias Grosser 1396f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 13978fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1398f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1399f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 140054491db6STobias Grosser // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 140154491db6STobias Grosser // "llvm.copysign". 140254491db6STobias Grosser const StringRef Name = F->getName(); 14038fc6cdfbSTobias Grosser 14048fc6cdfbSTobias Grosser if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0) 14058fc6cdfbSTobias Grosser return true; 14068fc6cdfbSTobias Grosser 140754491db6STobias Grosser return F->isIntrinsic() && 140854491db6STobias Grosser (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 140954491db6STobias Grosser Name.startswith("llvm.copysign")); 1410f291c8d5SSiddharth Bhat } 1411f291c8d5SSiddharth Bhat 1412f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1413f291c8d5SSiddharth Bhat /// 1414f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1415f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1416f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1417f291c8d5SSiddharth Bhat /// `Function`s. 1418f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1419f291c8d5SSiddharth Bhat 1420f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1421f291c8d5SSiddharth Bhat static SetVector<Function *> 14228fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 14238fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 1424f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1425f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1426f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1427f291c8d5SSiddharth Bhat if (F) { 14288fc6cdfbSTobias Grosser assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 14298fc6cdfbSTobias Grosser "Code should have bailed out by " 1430f291c8d5SSiddharth Bhat "this point if an invalid function " 1431f291c8d5SSiddharth Bhat "were present in a kernel."); 1432f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1433f291c8d5SSiddharth Bhat } 1434f291c8d5SSiddharth Bhat } 1435f291c8d5SSiddharth Bhat return SubtreeFunctions; 1436f291c8d5SSiddharth Bhat } 1437f291c8d5SSiddharth Bhat 1438*43df2020STobias Grosser std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 1439*43df2020STobias Grosser isl::space> 1440f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1441edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1442edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1443edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1444*43df2020STobias Grosser isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params(); 1445edb885cbSTobias Grosser SubtreeReferences References = { 1446*43df2020STobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(), 1447*43df2020STobias Grosser &ParamSpace}; 1448edb885cbSTobias Grosser 1449edb885cbSTobias Grosser for (const auto &I : IDToValue) 1450edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1451edb885cbSTobias Grosser 1452e53c924bSSiddharth Bhat // NOTE: this is populated in IslNodeBuilder::addParameters 1453e53c924bSSiddharth Bhat // See [Code generation of induction variables of loops outside Scops]. 1454e53c924bSSiddharth Bhat for (const auto &I : OutsideLoopIterations) 1455e53c924bSSiddharth Bhat SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1456e53c924bSSiddharth Bhat 1457edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1458edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1459edb885cbSTobias Grosser 1460e53c924bSSiddharth Bhat for (const SCEV *Expr : SCEVs) { 1461edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1462e53c924bSSiddharth Bhat findLoops(Expr, Loops); 1463e53c924bSSiddharth Bhat } 1464e53c924bSSiddharth Bhat 1465e53c924bSSiddharth Bhat Loops.remove_if([this](const Loop *L) { 1466e53c924bSSiddharth Bhat return S.contains(L) || L->contains(S.getEntry()); 1467e53c924bSSiddharth Bhat }); 1468edb885cbSTobias Grosser 1469edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1470d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1471edb885cbSTobias Grosser 1472b65ccc43STobias Grosser isl_space *Space = S.getParamSpace().release(); 1473edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1474edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1475edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1476edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1477edb885cbSTobias Grosser SubtreeValues.remove(Val); 1478edb885cbSTobias Grosser isl_id_free(Id); 1479edb885cbSTobias Grosser } 1480edb885cbSTobias Grosser isl_space_free(Space); 1481edb885cbSTobias Grosser 1482edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1483edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1484edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1485edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1486edb885cbSTobias Grosser SubtreeValues.remove(Val); 1487edb885cbSTobias Grosser isl_id_free(Id); 1488edb885cbSTobias Grosser } 1489edb885cbSTobias Grosser 1490f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1491f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1492f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1493f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1494f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1495f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1496f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1497f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1498f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 14998fc6cdfbSTobias Grosser 15008fc6cdfbSTobias Grosser bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 15018fc6cdfbSTobias Grosser 1502f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 15038fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1504f291c8d5SSiddharth Bhat 1505a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1506a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1507a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1508a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1509a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1510a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1511a1b2086aSSiddharth Bhat else 1512a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1513a1b2086aSSiddharth Bhat } 1514*43df2020STobias Grosser return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops, 1515*43df2020STobias Grosser ParamSpace); 1516edb885cbSTobias Grosser } 1517edb885cbSTobias Grosser 151874dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 151974dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 152074dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 152174dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 152274dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 152374dc3cb4STobias Grosser 152474dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 152574dc3cb4STobias Grosser DT.eraseNode(BB); 152674dc3cb4STobias Grosser } 152774dc3cb4STobias Grosser 152874dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 152974dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 153074dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 153174dc3cb4STobias Grosser if (L) 153274dc3cb4STobias Grosser SE.forgetLoop(L); 153374dc3cb4STobias Grosser } 153474dc3cb4STobias Grosser } 153574dc3cb4STobias Grosser 153674dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 153774dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 153874dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 153974dc3cb4STobias Grosser if (L) 154074dc3cb4STobias Grosser SE.forgetLoop(L); 154174dc3cb4STobias Grosser LI.removeBlock(&BB); 154274dc3cb4STobias Grosser } 154374dc3cb4STobias Grosser } 154474dc3cb4STobias Grosser 154579a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 154679a947c2STobias Grosser std::vector<Value *> Sizes; 15478ea1fc19STobias Grosser isl::ast_build Context = isl::ast_build::from_context(S.getContext()); 154879a947c2STobias Grosser 15494d5820d1SSiddharth Bhat isl::multi_pw_aff GridSizePwAffs = 15504d5820d1SSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size)); 155179a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 15524d5820d1SSiddharth Bhat isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i); 15534d5820d1SSiddharth Bhat isl::ast_expr GridSize = Context.expr_from(Size); 15544d5820d1SSiddharth Bhat Value *Res = ExprBuilder.create(GridSize.release()); 155579a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 155679a947c2STobias Grosser Sizes.push_back(Res); 155779a947c2STobias Grosser } 155879a947c2STobias Grosser 155979a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 156079a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 156179a947c2STobias Grosser 156279a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 156379a947c2STobias Grosser } 156479a947c2STobias Grosser 156579a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 156679a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 156779a947c2STobias Grosser std::vector<Value *> Sizes; 156879a947c2STobias Grosser 156979a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 157079a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 157179a947c2STobias Grosser Sizes.push_back(Res); 157279a947c2STobias Grosser } 157379a947c2STobias Grosser 157479a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 157579a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 157679a947c2STobias Grosser 157779a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 157879a947c2STobias Grosser } 157979a947c2STobias Grosser 1580a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1581a90be207SSiddharth Bhat Instruction *Param, int Index) { 1582a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1583a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1584a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1585a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1586a90be207SSiddharth Bhat } 1587a90be207SSiddharth Bhat 158857693272STobias Grosser Value * 158957693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 159057693272STobias Grosser SetVector<Value *> SubtreeValues) { 1591a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1592a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1593a90be207SSiddharth Bhat 1594a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 159579a947c2STobias Grosser 159679a947c2STobias Grosser BasicBlock *EntryBlock = 159779a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 159867726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 159979a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 160067726b32STobias Grosser Instruction *Parameters = new AllocaInst( 160167726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 160279a947c2STobias Grosser 160379a947c2STobias Grosser int Index = 0; 160479a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 160579a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 160679a947c2STobias Grosser continue; 160779a947c2STobias Grosser 160879a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1609206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 161079a947c2STobias Grosser 1611a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1612a90be207SSiddharth Bhat 1613abed4969SSiddharth Bhat Value *DevArray = nullptr; 1614c4a4af47SSiddharth Bhat if (PollyManagedMemory) { 1615b99c1171STobias Grosser DevArray = getManagedDeviceArray(&Prog->array[i], 1616b99c1171STobias Grosser const_cast<ScopArrayInfo *>(SAI)); 1617abed4969SSiddharth Bhat } else { 1618abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 161979a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1620abed4969SSiddharth Bhat } 1621abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1622abed4969SSiddharth Bhat "initialized"); 1623aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1624aaabbbf8STobias Grosser 1625aaabbbf8STobias Grosser if (Offset) { 1626aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1627aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1628aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1629aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1630aaabbbf8STobias Grosser } 1631fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1632fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1633aaabbbf8STobias Grosser 1634fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1635abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1636c4a4af47SSiddharth Bhat if (PollyManagedMemory) 1637abed4969SSiddharth Bhat ValPtr = DevArray; 1638abed4969SSiddharth Bhat else 1639abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1640abed4969SSiddharth Bhat 1641abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1642abed4969SSiddharth Bhat " to be stored into Parameters"); 1643fe74a7a1STobias Grosser Value *ValPtrCast = 1644fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1645fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1646fe74a7a1STobias Grosser } else { 164767726b32STobias Grosser Instruction *Param = 164867726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 164967726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 165079a947c2STobias Grosser EntryBlock->getTerminator()); 165179a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 165279a947c2STobias Grosser Value *ParamTyped = 165379a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 165479a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1655fe74a7a1STobias Grosser } 165679a947c2STobias Grosser Index++; 165779a947c2STobias Grosser } 165879a947c2STobias Grosser 1659a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1660a490147cSTobias Grosser 1661a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1662a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1663a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1664a490147cSTobias Grosser isl_id_free(Id); 1665a90be207SSiddharth Bhat 1666a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1667a90be207SSiddharth Bhat 166867726b32STobias Grosser Instruction *Param = 166967726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 167067726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1671a490147cSTobias Grosser EntryBlock->getTerminator()); 1672a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1673a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1674a490147cSTobias Grosser Index++; 1675a490147cSTobias Grosser } 1676a490147cSTobias Grosser 1677d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1678d8b94bcaSTobias Grosser 1679d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1680d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1681d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1682a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1683a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1684d8b94bcaSTobias Grosser isl_id_free(Id); 1685a90be207SSiddharth Bhat 1686a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1687a90be207SSiddharth Bhat 168867726b32STobias Grosser Instruction *Param = 168967726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 169067726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1691d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1692d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1693a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1694d8b94bcaSTobias Grosser Index++; 1695d8b94bcaSTobias Grosser } 1696d8b94bcaSTobias Grosser 169757693272STobias Grosser for (auto Val : SubtreeValues) { 1698a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1699a90be207SSiddharth Bhat 170067726b32STobias Grosser Instruction *Param = 170167726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 170267726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 170357693272STobias Grosser EntryBlock->getTerminator()); 170457693272STobias Grosser Builder.CreateStore(Val, Param); 1705a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1706a90be207SSiddharth Bhat Index++; 1707a90be207SSiddharth Bhat } 1708a90be207SSiddharth Bhat 1709a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1710a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1711a90be207SSiddharth Bhat Instruction *Param = 1712a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1713a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1714a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1715a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1716a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 171757693272STobias Grosser Index++; 171857693272STobias Grosser } 171957693272STobias Grosser 172079a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 172179a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 172279a947c2STobias Grosser Launch + "_params_i8ptr", Location); 172379a947c2STobias Grosser } 172479a947c2STobias Grosser 1725f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1726f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1727f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1728f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1729f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1730f291c8d5SSiddharth Bhat if (!Clone) 1731f291c8d5SSiddharth Bhat Clone = 1732f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1733f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1734f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1735f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1736f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1737f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1738f291c8d5SSiddharth Bhat } 1739f291c8d5SSiddharth Bhat } 174032837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 174132837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 174232837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 174332837fe3STobias Grosser isl_id_free(Id); 174432837fe3STobias Grosser isl_ast_node_free(KernelStmt); 174532837fe3STobias Grosser 1746bc653f20STobias Grosser if (Kernel->n_grid > 1) 1747bc653f20STobias Grosser DeepestParallel = 1748bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1749bc653f20STobias Grosser else 1750bc653f20STobias Grosser DeepestSequential = 1751bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1752bc653f20STobias Grosser 1753c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1754c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1755c1c6a2a6STobias Grosser 1756f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1757f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1758e53c924bSSiddharth Bhat SetVector<const Loop *> Loops; 1759*43df2020STobias Grosser isl::space ParamSpace; 1760*43df2020STobias Grosser std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) = 1761e53c924bSSiddharth Bhat getReferencesInKernel(Kernel); 1762edb885cbSTobias Grosser 1763*43df2020STobias Grosser // Add parameters that appear only in the access function to the kernel 1764*43df2020STobias Grosser // space. This is important to make sure that all isl_ids are passed as 1765*43df2020STobias Grosser // parameters to the kernel, even though we may not have all parameters 1766*43df2020STobias Grosser // in the context to improve compile time. 1767*43df2020STobias Grosser Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release()); 1768*43df2020STobias Grosser 176932837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 177032837fe3STobias Grosser 177132837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1772472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1773edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1774587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1775b06ff457STobias Grosser ScalarMap.clear(); 177632837fe3STobias Grosser 1777edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1778edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1779edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1780edb885cbSTobias Grosser for (const Loop *L : Loops) { 1781edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1782edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1783edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1784edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1785edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1786edb885cbSTobias Grosser SubtreeValues.insert(V); 1787edb885cbSTobias Grosser } 1788edb885cbSTobias Grosser 1789f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1790f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 179132837fe3STobias Grosser 179259ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 179359ab0705STobias Grosser 179451dfc275STobias Grosser finalizeKernelArguments(Kernel); 179574dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 17962f3073b5SPhilipp Schaad if (Arch == GPUArch::NVPTX64) 1797c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 179874dc3cb4STobias Grosser clearDominators(F); 179974dc3cb4STobias Grosser clearScalarEvolution(F); 180074dc3cb4STobias Grosser clearLoops(F); 180174dc3cb4STobias Grosser 1802472f9654STobias Grosser IDToValue = HostIDs; 180332837fe3STobias Grosser 1804b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1805b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1806edb885cbSTobias Grosser EscapeMap.clear(); 1807edb885cbSTobias Grosser IDToSAI.clear(); 180874dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 180974dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 18104d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 181174dc3cb4STobias Grosser LocalArrays.clear(); 1812edb885cbSTobias Grosser 181351dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 181451dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 181557693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 181679a947c2STobias Grosser 181779f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 181857793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 181957793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 182057793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 182179a947c2STobias Grosser 182279a947c2STobias Grosser Value *GridDimX, *GridDimY; 182379a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 182479a947c2STobias Grosser 182579a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 182679a947c2STobias Grosser BlockDimZ, Parameters); 182757793596STobias Grosser createCallFreeKernel(GPUKernel); 1828b513b491STobias Grosser 1829b513b491STobias Grosser for (auto Id : KernelIds) 1830b513b491STobias Grosser isl_id_free(Id); 1831b513b491STobias Grosser 1832b513b491STobias Grosser KernelIds.clear(); 183332837fe3STobias Grosser } 183432837fe3STobias Grosser 183532837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 183632837fe3STobias Grosser /// 183732837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 183832837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1839d277fedaSSiddharth Bhat std::string Ret = ""; 184032837fe3STobias Grosser 1841d277fedaSSiddharth Bhat if (!is64Bit) { 1842d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 184330caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1844d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1845d277fedaSSiddharth Bhat } else { 1846d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 184730caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1848d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1849d277fedaSSiddharth Bhat } 185032837fe3STobias Grosser 185132837fe3STobias Grosser return Ret; 185232837fe3STobias Grosser } 185332837fe3STobias Grosser 18542f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel. 18552f3073b5SPhilipp Schaad /// 18562f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture? 18572f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) { 18582f3073b5SPhilipp Schaad std::string Ret = ""; 18592f3073b5SPhilipp Schaad 18602f3073b5SPhilipp Schaad if (!is64Bit) { 18612f3073b5SPhilipp Schaad Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 186230caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 18632f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18642f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18652f3073b5SPhilipp Schaad } else { 18662f3073b5SPhilipp Schaad Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 186730caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 18682f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18692f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18702f3073b5SPhilipp Schaad } 18712f3073b5SPhilipp Schaad 18722f3073b5SPhilipp Schaad return Ret; 18732f3073b5SPhilipp Schaad } 18742f3073b5SPhilipp Schaad 1875edb885cbSTobias Grosser Function * 1876edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1877edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 187832837fe3STobias Grosser std::vector<Type *> Args; 187979f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 188032837fe3STobias Grosser 18812f3073b5SPhilipp Schaad std::vector<Metadata *> MemoryType; 18822f3073b5SPhilipp Schaad 188332837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 188432837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 188532837fe3STobias Grosser continue; 188632837fe3STobias Grosser 1887fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1888fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1889206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1890fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 18912f3073b5SPhilipp Schaad MemoryType.push_back( 18922f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1893fe74a7a1STobias Grosser } else { 1894d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1895d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 18962f3073b5SPhilipp Schaad MemoryType.push_back( 18972f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 189832837fe3STobias Grosser } 1899fe74a7a1STobias Grosser } 190032837fe3STobias Grosser 1901f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1902f6044bd0STobias Grosser 19032f3073b5SPhilipp Schaad for (long i = 0; i < NumHostIters; i++) { 1904f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 19052f3073b5SPhilipp Schaad MemoryType.push_back( 19062f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19072f3073b5SPhilipp Schaad } 1908f6044bd0STobias Grosser 1909c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1910c84a1995STobias Grosser 1911cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1912cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1913cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1914cf66ef26STobias Grosser isl_id_free(Id); 1915cf66ef26STobias Grosser Args.push_back(Val->getType()); 19162f3073b5SPhilipp Schaad MemoryType.push_back( 19172f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1918cf66ef26STobias Grosser } 1919c84a1995STobias Grosser 19202f3073b5SPhilipp Schaad for (auto *V : SubtreeValues) { 1921edb885cbSTobias Grosser Args.push_back(V->getType()); 19222f3073b5SPhilipp Schaad MemoryType.push_back( 19232f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19242f3073b5SPhilipp Schaad } 1925edb885cbSTobias Grosser 192632837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 192732837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 192832837fe3STobias Grosser GPUModule.get()); 192917f01968SSiddharth Bhat 19302f3073b5SPhilipp Schaad std::vector<Metadata *> EmptyStrings; 19312f3073b5SPhilipp Schaad 19322f3073b5SPhilipp Schaad for (unsigned int i = 0; i < MemoryType.size(); i++) { 19332f3073b5SPhilipp Schaad EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 19342f3073b5SPhilipp Schaad } 19352f3073b5SPhilipp Schaad 19362f3073b5SPhilipp Schaad if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 19372f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_addr_space", 19382f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), MemoryType)); 19392f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_name", 19402f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19412f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_access_qual", 19422f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19432f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type", 19442f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19452f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type_qual", 19462f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19472f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_base_type", 19482f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19492f3073b5SPhilipp Schaad } 19502f3073b5SPhilipp Schaad 195117f01968SSiddharth Bhat switch (Arch) { 195217f01968SSiddharth Bhat case GPUArch::NVPTX64: 195332837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 195417f01968SSiddharth Bhat break; 19552f3073b5SPhilipp Schaad case GPUArch::SPIR32: 19562f3073b5SPhilipp Schaad case GPUArch::SPIR64: 19572f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_KERNEL); 19582f3073b5SPhilipp Schaad break; 195917f01968SSiddharth Bhat } 196032837fe3STobias Grosser 196132837fe3STobias Grosser auto Arg = FN->arg_begin(); 196232837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 196332837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 196432837fe3STobias Grosser continue; 196532837fe3STobias Grosser 1966edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1967edb885cbSTobias Grosser 1968edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1969206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 1970206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 1971edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1972edb885cbSTobias Grosser Value *Val = &*Arg; 1973edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1974edb885cbSTobias Grosser isl_ast_build *Build = 1975edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1976f5aff704SRoman Gareev Sizes.push_back(nullptr); 1977edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1978edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 19799e3db2b7SSiddharth Bhat Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1980edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1981edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1982edb885cbSTobias Grosser } 1983edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 19844d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 198574dc3cb4STobias Grosser LocalArrays.push_back(Val); 1986edb885cbSTobias Grosser 1987edb885cbSTobias Grosser isl_ast_build_free(Build); 1988b513b491STobias Grosser KernelIds.push_back(Id); 1989edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 199032837fe3STobias Grosser Arg++; 199132837fe3STobias Grosser } 199232837fe3STobias Grosser 1993f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1994f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1995f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1996f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1997f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1998f6044bd0STobias Grosser Arg++; 1999f6044bd0STobias Grosser } 2000f6044bd0STobias Grosser 2001c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 2002c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 2003c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 200412453403STobias Grosser Value *Val = IDToValue[Id]; 200512453403STobias Grosser ValueMap[Val] = &*Arg; 2006c84a1995STobias Grosser IDToValue[Id] = &*Arg; 2007c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2008c84a1995STobias Grosser Arg++; 2009c84a1995STobias Grosser } 2010c84a1995STobias Grosser 2011edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 2012edb885cbSTobias Grosser Arg->setName(V->getName()); 2013edb885cbSTobias Grosser ValueMap[V] = &*Arg; 2014edb885cbSTobias Grosser Arg++; 2015edb885cbSTobias Grosser } 2016edb885cbSTobias Grosser 201732837fe3STobias Grosser return FN; 201832837fe3STobias Grosser } 201932837fe3STobias Grosser 2020472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 202117f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 202217f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 2023472f9654STobias Grosser 202417f01968SSiddharth Bhat switch (Arch) { 20252f3073b5SPhilipp Schaad case GPUArch::SPIR64: 20262f3073b5SPhilipp Schaad case GPUArch::SPIR32: 20272f3073b5SPhilipp Schaad llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 202817f01968SSiddharth Bhat case GPUArch::NVPTX64: 202917f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 203017f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 203117f01968SSiddharth Bhat 203217f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 203317f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 203417f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 203517f01968SSiddharth Bhat break; 203617f01968SSiddharth Bhat } 2037472f9654STobias Grosser 2038472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2039472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 2040472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2041472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2042472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2043472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2044472f9654STobias Grosser IDToValue[Id] = Val; 2045472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2046472f9654STobias Grosser }; 2047472f9654STobias Grosser 2048472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 2049472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2050472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 2051472f9654STobias Grosser } 2052472f9654STobias Grosser 2053472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 2054472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2055472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 2056472f9654STobias Grosser } 2057472f9654STobias Grosser } 2058472f9654STobias Grosser 20592f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 20602f3073b5SPhilipp Schaad const char *GroupName[3] = {"__gen_ocl_get_group_id0", 20612f3073b5SPhilipp Schaad "__gen_ocl_get_group_id1", 20622f3073b5SPhilipp Schaad "__gen_ocl_get_group_id2"}; 20632f3073b5SPhilipp Schaad 20642f3073b5SPhilipp Schaad const char *LocalName[3] = {"__gen_ocl_get_local_id0", 20652f3073b5SPhilipp Schaad "__gen_ocl_get_local_id1", 20662f3073b5SPhilipp Schaad "__gen_ocl_get_local_id2"}; 20672f3073b5SPhilipp Schaad 20682f3073b5SPhilipp Schaad auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 20692f3073b5SPhilipp Schaad Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 20702f3073b5SPhilipp Schaad Function *FN = M->getFunction(Name); 20712f3073b5SPhilipp Schaad 20722f3073b5SPhilipp Schaad // If FN is not available, declare it. 20732f3073b5SPhilipp Schaad if (!FN) { 20742f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 20752f3073b5SPhilipp Schaad std::vector<Type *> Args; 20762f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 20772f3073b5SPhilipp Schaad FN = Function::Create(Ty, Linkage, Name, M); 20782f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_FUNC); 20792f3073b5SPhilipp Schaad } 20802f3073b5SPhilipp Schaad 20812f3073b5SPhilipp Schaad Value *Val = Builder.CreateCall(FN, {}); 20822f3073b5SPhilipp Schaad Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 20832f3073b5SPhilipp Schaad IDToValue[Id] = Val; 20842f3073b5SPhilipp Schaad KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 20852f3073b5SPhilipp Schaad }; 20862f3073b5SPhilipp Schaad 20872f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_grid; ++i) 20882f3073b5SPhilipp Schaad createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 20892f3073b5SPhilipp Schaad 20902f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_block; ++i) 20912f3073b5SPhilipp Schaad createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 20922f3073b5SPhilipp Schaad } 20932f3073b5SPhilipp Schaad 209400bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 209500bb5a99STobias Grosser auto Arg = FN->arg_begin(); 209600bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 209700bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 209800bb5a99STobias Grosser continue; 209900bb5a99STobias Grosser 210000bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2101206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2102206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 210300bb5a99STobias Grosser isl_id_free(Id); 210400bb5a99STobias Grosser 210500bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 210600bb5a99STobias Grosser Arg++; 210700bb5a99STobias Grosser continue; 210800bb5a99STobias Grosser } 210900bb5a99STobias Grosser 2110fe74a7a1STobias Grosser Value *Val = &*Arg; 2111fe74a7a1STobias Grosser 2112fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 211300bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 2114fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2115fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 2116fe74a7a1STobias Grosser } 2117fe74a7a1STobias Grosser 2118fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 211900bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 212000bb5a99STobias Grosser 212100bb5a99STobias Grosser Arg++; 212200bb5a99STobias Grosser } 212300bb5a99STobias Grosser } 212400bb5a99STobias Grosser 212551dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 212651dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 212751dfc275STobias Grosser auto Arg = FN->arg_begin(); 212851dfc275STobias Grosser 212951dfc275STobias Grosser bool StoredScalar = false; 213051dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 213151dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 213251dfc275STobias Grosser continue; 213351dfc275STobias Grosser 213451dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2135206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2136206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 213751dfc275STobias Grosser isl_id_free(Id); 213851dfc275STobias Grosser 213951dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 214051dfc275STobias Grosser Arg++; 214151dfc275STobias Grosser continue; 214251dfc275STobias Grosser } 214351dfc275STobias Grosser 214451dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 214551dfc275STobias Grosser Arg++; 214651dfc275STobias Grosser continue; 214751dfc275STobias Grosser } 214851dfc275STobias Grosser 214951dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 215051dfc275STobias Grosser Value *ArgPtr = &*Arg; 215151dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 215251dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 215351dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 215451dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 215551dfc275STobias Grosser StoredScalar = true; 215651dfc275STobias Grosser 215751dfc275STobias Grosser Arg++; 215851dfc275STobias Grosser } 215951dfc275STobias Grosser 2160638316daSSiddharth Bhat if (StoredScalar) { 216151dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 216251dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 216351dfc275STobias Grosser /// To support this case we need to store these scalars back at each 216451dfc275STobias Grosser /// memory store or at least before each kernel barrier. 2165638316daSSiddharth Bhat if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 216651dfc275STobias Grosser BuildSuccessful = 0; 2167638316daSSiddharth Bhat DEBUG( 2168638316daSSiddharth Bhat dbgs() << getUniqueScopName(&S) 2169638316daSSiddharth Bhat << " has a store to a scalar value that" 2170638316daSSiddharth Bhat " would be undefined to run in parallel. Bailing out.\n";); 2171638316daSSiddharth Bhat } 2172638316daSSiddharth Bhat } 217351dfc275STobias Grosser } 217451dfc275STobias Grosser 2175b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2176b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2177b513b491STobias Grosser 2178b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 2179b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 2180b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2181206e9e3bSTobias Grosser Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2182b513b491STobias Grosser 2183f919d8b3STobias Grosser Type *ArrayTy = EleTy; 2184b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 2185b513b491STobias Grosser 2186f5aff704SRoman Gareev Sizes.push_back(nullptr); 2187928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2188b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2189f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 2190b513b491STobias Grosser isl_val_free(Val); 2191b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2192928d7573STobias Grosser } 2193928d7573STobias Grosser 2194928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 2195928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2196928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 2197928d7573STobias Grosser isl_val_free(Val); 2198b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 2199b513b491STobias Grosser } 2200b513b491STobias Grosser 2201130ca30fSTobias Grosser const ScopArrayInfo *SAI; 2202130ca30fSTobias Grosser Value *Allocation; 2203130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 2204130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 2205130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2206130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2207130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2208f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2209f919d8b3STobias Grosser 2210130ca30fSTobias Grosser Allocation = GlobalVar; 2211130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 2212130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2213130ca30fSTobias Grosser } else { 2214130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 2215130ca30fSTobias Grosser } 22164d5a9172STobias Grosser SAI = 22174d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2218b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2219130ca30fSTobias Grosser IDToValue[Id] = Allocation; 2220130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 2221b513b491STobias Grosser KernelIds.push_back(Id); 2222b513b491STobias Grosser IDToSAI[Id] = SAI; 2223b513b491STobias Grosser } 2224b513b491STobias Grosser } 2225b513b491STobias Grosser 2226f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 2227f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2228f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 222979f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 223032837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 223117f01968SSiddharth Bhat 223217f01968SSiddharth Bhat switch (Arch) { 223317f01968SSiddharth Bhat case GPUArch::NVPTX64: 223417f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 223532837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 223617f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 223717f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 223832837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 223917f01968SSiddharth Bhat break; 22402f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22412f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 22422f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 22432f3073b5SPhilipp Schaad break; 22442f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22452f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 22462f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 22472f3073b5SPhilipp Schaad break; 224817f01968SSiddharth Bhat } 224932837fe3STobias Grosser 2250edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 225132837fe3STobias Grosser 225259ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 225332837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 225432837fe3STobias Grosser 225559ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 225659ab0705STobias Grosser 225732837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 225832837fe3STobias Grosser Builder.CreateRetVoid(); 225932837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2260472f9654STobias Grosser 2261629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 2262629109b6STobias Grosser 226300bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2264b513b491STobias Grosser createKernelVariables(Kernel, FN); 22652f3073b5SPhilipp Schaad 22662f3073b5SPhilipp Schaad switch (Arch) { 22672f3073b5SPhilipp Schaad case GPUArch::NVPTX64: 2268472f9654STobias Grosser insertKernelIntrinsics(Kernel); 22692f3073b5SPhilipp Schaad break; 22702f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22712f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22722f3073b5SPhilipp Schaad insertKernelCallsSPIR(Kernel); 22732f3073b5SPhilipp Schaad break; 22742f3073b5SPhilipp Schaad } 227532837fe3STobias Grosser } 227632837fe3STobias Grosser 227774dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 227817f01968SSiddharth Bhat llvm::Triple GPUTriple; 227917f01968SSiddharth Bhat 228017f01968SSiddharth Bhat switch (Arch) { 228117f01968SSiddharth Bhat case GPUArch::NVPTX64: 228217f01968SSiddharth Bhat switch (Runtime) { 228317f01968SSiddharth Bhat case GPURuntime::CUDA: 228417f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 228517f01968SSiddharth Bhat break; 228617f01968SSiddharth Bhat case GPURuntime::OpenCL: 228717f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 228817f01968SSiddharth Bhat break; 228917f01968SSiddharth Bhat } 229017f01968SSiddharth Bhat break; 22912f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22922f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22932f3073b5SPhilipp Schaad std::string SPIRAssembly; 22942f3073b5SPhilipp Schaad raw_string_ostream IROstream(SPIRAssembly); 22952f3073b5SPhilipp Schaad IROstream << *GPUModule; 22962f3073b5SPhilipp Schaad IROstream.flush(); 22972f3073b5SPhilipp Schaad return SPIRAssembly; 229817f01968SSiddharth Bhat } 229917f01968SSiddharth Bhat 230074dc3cb4STobias Grosser std::string ErrMsg; 230174dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 230274dc3cb4STobias Grosser 230374dc3cb4STobias Grosser if (!GPUTarget) { 230474dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 230574dc3cb4STobias Grosser return ""; 230674dc3cb4STobias Grosser } 230774dc3cb4STobias Grosser 230874dc3cb4STobias Grosser TargetOptions Options; 230974dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 231017f01968SSiddharth Bhat 231117f01968SSiddharth Bhat std::string subtarget; 231217f01968SSiddharth Bhat 231317f01968SSiddharth Bhat switch (Arch) { 231417f01968SSiddharth Bhat case GPUArch::NVPTX64: 231517f01968SSiddharth Bhat subtarget = CudaVersion; 231617f01968SSiddharth Bhat break; 23172f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23182f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23192f3073b5SPhilipp Schaad llvm_unreachable("No subtarget for SPIR architecture"); 232017f01968SSiddharth Bhat } 232117f01968SSiddharth Bhat 232217f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 232317f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 232474dc3cb4STobias Grosser 232574dc3cb4STobias Grosser SmallString<0> ASMString; 232674dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 232774dc3cb4STobias Grosser llvm::legacy::PassManager PM; 232874dc3cb4STobias Grosser 232974dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 233074dc3cb4STobias Grosser 233174dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 233274dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 233374dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 233474dc3cb4STobias Grosser return ""; 233574dc3cb4STobias Grosser } 233674dc3cb4STobias Grosser 233774dc3cb4STobias Grosser PM.run(*GPUModule); 233874dc3cb4STobias Grosser 233974dc3cb4STobias Grosser return ASMStream.str(); 234074dc3cb4STobias Grosser } 234174dc3cb4STobias Grosser 23428fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() { 23435b307cdbSTobias Grosser bool RequiresLibDevice = false; 23448fc6cdfbSTobias Grosser for (Function &F : GPUModule->functions()) { 23458fc6cdfbSTobias Grosser if (!F.isDeclaration()) 23468fc6cdfbSTobias Grosser continue; 23478fc6cdfbSTobias Grosser 23488fc6cdfbSTobias Grosser std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F); 23498fc6cdfbSTobias Grosser if (CUDALibDeviceFunc.length() != 0) { 23508fc6cdfbSTobias Grosser F.setName(CUDALibDeviceFunc); 23515b307cdbSTobias Grosser RequiresLibDevice = true; 23528fc6cdfbSTobias Grosser } 23538fc6cdfbSTobias Grosser } 23548fc6cdfbSTobias Grosser 23555b307cdbSTobias Grosser return RequiresLibDevice; 23568fc6cdfbSTobias Grosser } 23578fc6cdfbSTobias Grosser 23588fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() { 23598fc6cdfbSTobias Grosser if (Arch != GPUArch::NVPTX64) 23608fc6cdfbSTobias Grosser return; 23618fc6cdfbSTobias Grosser 23628fc6cdfbSTobias Grosser if (requiresCUDALibDevice()) { 23638fc6cdfbSTobias Grosser SMDiagnostic Error; 23648fc6cdfbSTobias Grosser 23658fc6cdfbSTobias Grosser errs() << CUDALibDevice << "\n"; 23668fc6cdfbSTobias Grosser auto LibDeviceModule = 23678fc6cdfbSTobias Grosser parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 23688fc6cdfbSTobias Grosser 23698fc6cdfbSTobias Grosser if (!LibDeviceModule) { 23708fc6cdfbSTobias Grosser BuildSuccessful = false; 23718fc6cdfbSTobias Grosser report_fatal_error("Could not find or load libdevice. Skipping GPU " 23728fc6cdfbSTobias Grosser "kernel generation. Please set -polly-acc-libdevice " 23738fc6cdfbSTobias Grosser "accordingly.\n"); 23748fc6cdfbSTobias Grosser return; 23758fc6cdfbSTobias Grosser } 23768fc6cdfbSTobias Grosser 23778fc6cdfbSTobias Grosser Linker L(*GPUModule); 23788fc6cdfbSTobias Grosser 23798fc6cdfbSTobias Grosser // Set an nvptx64 target triple to avoid linker warnings. The original 23808fc6cdfbSTobias Grosser // triple of the libdevice files are nvptx-unknown-unknown. 23818fc6cdfbSTobias Grosser LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 23828fc6cdfbSTobias Grosser L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 23838fc6cdfbSTobias Grosser } 23848fc6cdfbSTobias Grosser } 23858fc6cdfbSTobias Grosser 238657793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 238765d7f72fSSiddharth Bhat 23885857b701STobias Grosser if (verifyModule(*GPUModule)) { 238965d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 239065d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2391a0fb8b23SSiddharth Bhat DEBUG(dbgs() << "verifyModule Error:\n"; 2392a0fb8b23SSiddharth Bhat verifyModule(*GPUModule, &dbgs());); 239365d7f72fSSiddharth Bhat 239465d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 239565d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 239665d7f72fSSiddharth Bhat 23975857b701STobias Grosser BuildSuccessful = false; 23985857b701STobias Grosser return ""; 23995857b701STobias Grosser } 240032837fe3STobias Grosser 24018fc6cdfbSTobias Grosser addCUDALibDevice(); 24028fc6cdfbSTobias Grosser 240332837fe3STobias Grosser if (DumpKernelIR) 240432837fe3STobias Grosser outs() << *GPUModule << "\n"; 240532837fe3STobias Grosser 24062f3073b5SPhilipp Schaad if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 24079a18d559STobias Grosser // Optimize module. 24089a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 24099a18d559STobias Grosser PassManagerBuilder PassBuilder; 24109a18d559STobias Grosser PassBuilder.OptLevel = 3; 24119a18d559STobias Grosser PassBuilder.SizeLevel = 0; 24129a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 24139a18d559STobias Grosser OptPasses.run(*GPUModule); 24142f3073b5SPhilipp Schaad } 24159a18d559STobias Grosser 241674dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 241774dc3cb4STobias Grosser 241874dc3cb4STobias Grosser if (DumpKernelASM) 241974dc3cb4STobias Grosser outs() << Assembly << "\n"; 242074dc3cb4STobias Grosser 242132837fe3STobias Grosser GPUModule.release(); 2422472f9654STobias Grosser KernelIDs.clear(); 242357793596STobias Grosser 242457793596STobias Grosser return Assembly; 242532837fe3STobias Grosser } 2426eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2427eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an 2428eadf76d3SSiddharth Bhat /// `isl_pw_aff_list` from. We expect an rvalue ref because 2429eadf76d3SSiddharth Bhat /// all the isl_pw_aff are used up by this function. 2430eadf76d3SSiddharth Bhat /// 2431eadf76d3SSiddharth Bhat /// @returns The `isl_pw_aff_list`. 2432eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list * 2433eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context, 2434eadf76d3SSiddharth Bhat const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2435eadf76d3SSiddharth Bhat isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2436eadf76d3SSiddharth Bhat 2437eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2438eadf76d3SSiddharth Bhat List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2439eadf76d3SSiddharth Bhat } 2440eadf76d3SSiddharth Bhat return List; 2441eadf76d3SSiddharth Bhat } 2442eadf76d3SSiddharth Bhat 2443eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions. 2444eadf76d3SSiddharth Bhat /// 2445eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to 2446eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the 2447eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2448eadf76d3SSiddharth Bhat /// with the given `SeedSpace`. 2449eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions we want to align. 2450eadf76d3SSiddharth Bhat /// This is an rvalue reference because the entire vector is 2451eadf76d3SSiddharth Bhat /// used up by the end of the operation. 2452eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with. 2453eadf76d3SSiddharth Bhat /// @returns A std::pair, whose first element is the aligned space, 2454eadf76d3SSiddharth Bhat /// whose second element is the vector of aligned piecewise 2455eadf76d3SSiddharth Bhat /// affines. 2456eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2457eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2458eadf76d3SSiddharth Bhat __isl_take isl_space *SeedSpace) { 2459eadf76d3SSiddharth Bhat assert(SeedSpace && "Invalid seed space given."); 2460eadf76d3SSiddharth Bhat 2461eadf76d3SSiddharth Bhat isl_space *AlignSpace = SeedSpace; 2462eadf76d3SSiddharth Bhat for (isl_pw_aff *PwAff : PwAffs) { 2463eadf76d3SSiddharth Bhat isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2464eadf76d3SSiddharth Bhat AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2465eadf76d3SSiddharth Bhat } 2466eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AdjustedPwAffs; 2467eadf76d3SSiddharth Bhat 2468eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2469eadf76d3SSiddharth Bhat isl_pw_aff *Adjusted = PwAffs[i]; 2470eadf76d3SSiddharth Bhat assert(Adjusted && "Invalid pw_aff given."); 2471eadf76d3SSiddharth Bhat Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2472eadf76d3SSiddharth Bhat AdjustedPwAffs.push_back(Adjusted); 2473eadf76d3SSiddharth Bhat } 2474eadf76d3SSiddharth Bhat return std::make_pair(AlignSpace, AdjustedPwAffs); 2475eadf76d3SSiddharth Bhat } 247632837fe3STobias Grosser 24779dfe4e7cSTobias Grosser namespace { 24789dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 24799dfe4e7cSTobias Grosser public: 24809dfe4e7cSTobias Grosser static char ID; 24819dfe4e7cSTobias Grosser 248217f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 248317f01968SSiddharth Bhat 248417f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 248517f01968SSiddharth Bhat 2486e938517eSTobias Grosser /// The scop that is currently processed. 2487e938517eSTobias Grosser Scop *S; 2488e938517eSTobias Grosser 248938fc0aedSTobias Grosser LoopInfo *LI; 249038fc0aedSTobias Grosser DominatorTree *DT; 249138fc0aedSTobias Grosser ScalarEvolution *SE; 249238fc0aedSTobias Grosser const DataLayout *DL; 249338fc0aedSTobias Grosser RegionInfo *RI; 249438fc0aedSTobias Grosser 24959dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 24969dfe4e7cSTobias Grosser 2497e938517eSTobias Grosser /// Construct compilation options for PPCG. 2498e938517eSTobias Grosser /// 2499e938517eSTobias Grosser /// @returns The compilation options. 2500e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2501e938517eSTobias Grosser auto DebugOptions = 2502e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2503e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2504e938517eSTobias Grosser 2505e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2506e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2507e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2508e938517eSTobias Grosser DebugOptions->dump_sizes = false; 25098950ceadSTobias Grosser DebugOptions->verbose = false; 2510e938517eSTobias Grosser 2511e938517eSTobias Grosser Options->debug = DebugOptions; 2512e938517eSTobias Grosser 25139e3db2b7SSiddharth Bhat Options->group_chains = false; 2514e938517eSTobias Grosser Options->reschedule = true; 2515e938517eSTobias Grosser Options->scale_tile_loops = false; 2516e938517eSTobias Grosser Options->wrap = false; 2517e938517eSTobias Grosser 2518e938517eSTobias Grosser Options->non_negative_parameters = false; 2519e938517eSTobias Grosser Options->ctx = nullptr; 2520e938517eSTobias Grosser Options->sizes = nullptr; 2521e938517eSTobias Grosser 25229e3db2b7SSiddharth Bhat Options->tile = true; 25234eaedde5STobias Grosser Options->tile_size = 32; 25244eaedde5STobias Grosser 25259e3db2b7SSiddharth Bhat Options->isolate_full_tiles = false; 25269e3db2b7SSiddharth Bhat 2527130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2528b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2529b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2530e938517eSTobias Grosser 2531e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2532e938517eSTobias Grosser Options->openmp = false; 2533e938517eSTobias Grosser Options->linearize_device_arrays = true; 25349e3db2b7SSiddharth Bhat Options->allow_gnu_extensions = false; 2535e938517eSTobias Grosser 25369e3db2b7SSiddharth Bhat Options->unroll_copy_shared = false; 25379e3db2b7SSiddharth Bhat Options->unroll_gpu_tile = false; 25389e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25399e3db2b7SSiddharth Bhat 25409e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25419e3db2b7SSiddharth Bhat Options->hybrid = false; 2542e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2543e938517eSTobias Grosser Options->opencl_use_gpu = false; 2544e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2545e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2546e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2547e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2548e938517eSTobias Grosser 2549e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2550e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2551e938517eSTobias Grosser 2552e938517eSTobias Grosser return Options; 2553e938517eSTobias Grosser } 2554e938517eSTobias Grosser 2555f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2556f384594dSTobias Grosser /// 2557f384594dSTobias Grosser /// Instead of a normal access of the form: 2558f384594dSTobias Grosser /// 2559f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2560f384594dSTobias Grosser /// 2561f384594dSTobias Grosser /// a tagged access has the form 2562f384594dSTobias Grosser /// 2563f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2564f384594dSTobias Grosser /// 2565f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2566f384594dSTobias Grosser /// triggered the access. 2567f384594dSTobias Grosser /// 2568f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2569f384594dSTobias Grosser /// 2570f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2571f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2572b65ccc43STobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release()); 2573f384594dSTobias Grosser 2574f384594dSTobias Grosser for (auto &Stmt : *S) 2575f384594dSTobias Grosser for (auto &Acc : Stmt) 2576f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 25771515f6b9STobias Grosser isl_map *Relation = Acc->getAccessRelation().release(); 2578dcf8d696STobias Grosser Relation = 2579dcf8d696STobias Grosser isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2580f384594dSTobias Grosser 2581f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2582f384594dSTobias Grosser Space = isl_space_range(Space); 2583f384594dSTobias Grosser Space = isl_space_from_range(Space); 2584fe46c3ffSTobias Grosser Space = 2585fe46c3ffSTobias Grosser isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2586f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2587f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2588f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2589f384594dSTobias Grosser } 2590f384594dSTobias Grosser 2591f384594dSTobias Grosser return Accesses; 2592f384594dSTobias Grosser } 2593f384594dSTobias Grosser 2594f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2595f384594dSTobias Grosser /// 2596f384594dSTobias Grosser /// @see getTaggedAccesses 2597f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2598f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2599f384594dSTobias Grosser } 2600f384594dSTobias Grosser 2601f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2602f384594dSTobias Grosser /// 2603f384594dSTobias Grosser /// @see getTaggedAccesses 2604f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2605f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2606f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2607f384594dSTobias Grosser } 2608f384594dSTobias Grosser 2609f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2610f384594dSTobias Grosser /// 2611f384594dSTobias Grosser /// @see getTaggedAccesses 2612f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2613f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2614f384594dSTobias Grosser } 2615f384594dSTobias Grosser 2616aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2617aef5196fSTobias Grosser /// 2618aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2619aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2620aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2621aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2622aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2623aef5196fSTobias Grosser /// the data format that ppcg expects. 2624aef5196fSTobias Grosser /// 2625aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2626aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2627aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2628bd81a7eeSTobias Grosser S->getIslCtx(), 2629bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2630aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2631aef5196fSTobias Grosser 263225271b91STobias Grosser for (const SCEV *P : S->parameters()) { 26339a63570bSTobias Grosser isl_id *Id = S->getIdForParam(P).release(); 2634aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2635aef5196fSTobias Grosser } 2636aef5196fSTobias Grosser 2637aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 263877eef90fSTobias Grosser auto Id = Array->getBasePtrId().release(); 2639aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2640aef5196fSTobias Grosser } 2641aef5196fSTobias Grosser 2642aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2643aef5196fSTobias Grosser 2644aef5196fSTobias Grosser return Names; 2645aef5196fSTobias Grosser } 2646aef5196fSTobias Grosser 2647ec02acfbSTobias Grosser /// Remove unreferenced parameter dimensions from union_map. 2648ec02acfbSTobias Grosser isl::union_map removeUnusedParameters(isl::union_map UMap) { 2649ec02acfbSTobias Grosser auto New = isl::union_map::empty(isl::space(UMap.get_ctx(), 0, 0)); 2650ec02acfbSTobias Grosser 2651ec02acfbSTobias Grosser auto RemoveUnusedDims = [&New](isl::map S) -> isl::stat { 2652ec02acfbSTobias Grosser int Removed = 0; 2653ec02acfbSTobias Grosser int NumDims = S.dim(isl::dim::param); 2654ec02acfbSTobias Grosser for (long i = 0; i < NumDims; i++) { 2655ec02acfbSTobias Grosser const int Dim = i - Removed; 2656ec02acfbSTobias Grosser if (!S.involves_dims(isl::dim::param, Dim, 1)) { 2657ec02acfbSTobias Grosser S = S.remove_dims(isl::dim::param, Dim, 1); 2658ec02acfbSTobias Grosser Removed++; 2659ec02acfbSTobias Grosser } 2660ec02acfbSTobias Grosser } 2661ec02acfbSTobias Grosser New = New.unite(S); 2662ec02acfbSTobias Grosser return isl::stat::ok; 2663ec02acfbSTobias Grosser }; 2664ec02acfbSTobias Grosser 2665ec02acfbSTobias Grosser UMap.foreach_map(RemoveUnusedDims); 2666ec02acfbSTobias Grosser return New; 2667ec02acfbSTobias Grosser } 2668ec02acfbSTobias Grosser 2669ec02acfbSTobias Grosser /// Remove unreferenced parameter dimensions from union_set. 2670ec02acfbSTobias Grosser isl::union_set removeUnusedParameters(isl::union_set USet) { 2671ec02acfbSTobias Grosser auto New = isl::union_set::empty(isl::space(USet.get_ctx(), 0, 0)); 2672ec02acfbSTobias Grosser 2673ec02acfbSTobias Grosser auto RemoveUnusedDims = [&New](isl::set S) -> isl::stat { 2674ec02acfbSTobias Grosser int Removed = 0; 2675ec02acfbSTobias Grosser int NumDims = S.dim(isl::dim::param); 2676ec02acfbSTobias Grosser for (long i = 0; i < NumDims; i++) { 2677ec02acfbSTobias Grosser const int Dim = i - Removed; 2678ec02acfbSTobias Grosser if (!S.involves_dims(isl::dim::param, Dim, 1)) { 2679ec02acfbSTobias Grosser S = S.remove_dims(isl::dim::param, Dim, 1); 2680ec02acfbSTobias Grosser Removed++; 2681ec02acfbSTobias Grosser } 2682ec02acfbSTobias Grosser } 2683ec02acfbSTobias Grosser New = New.unite(S); 2684ec02acfbSTobias Grosser return isl::stat::ok; 2685ec02acfbSTobias Grosser }; 2686ec02acfbSTobias Grosser 2687ec02acfbSTobias Grosser USet.foreach_set(RemoveUnusedDims); 2688ec02acfbSTobias Grosser return New; 2689ec02acfbSTobias Grosser } 2690ec02acfbSTobias Grosser 2691ec02acfbSTobias Grosser /// Simplify PPCG scop to improve compile time. 2692ec02acfbSTobias Grosser /// 2693ec02acfbSTobias Grosser /// We drop unused parameter dimensions to reduce the size of the sets we are 2694ec02acfbSTobias Grosser /// working with. Especially the computed dependences tend to accumulate a lot 2695ec02acfbSTobias Grosser /// of parameters that are present in the input memory accesses, but often are 2696ec02acfbSTobias Grosser /// not necessary to express the actual dependences. As isl represents maps 2697ec02acfbSTobias Grosser /// and sets with dense matrices, reducing the dimensionality of isl sets 2698ec02acfbSTobias Grosser /// commonly reduces code generation performance. 2699ec02acfbSTobias Grosser void simplifyPPCGScop(ppcg_scop *PPCGScop) { 2700ec02acfbSTobias Grosser PPCGScop->domain = 2701ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->domain)).release(); 2702ec02acfbSTobias Grosser 2703ec02acfbSTobias Grosser PPCGScop->dep_forced = 2704ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->dep_forced)).release(); 2705ec02acfbSTobias Grosser PPCGScop->dep_false = 2706ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->dep_false)).release(); 2707ec02acfbSTobias Grosser PPCGScop->dep_flow = 2708ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->dep_flow)).release(); 2709ec02acfbSTobias Grosser PPCGScop->tagged_dep_flow = 2710ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->tagged_dep_flow)) 2711ec02acfbSTobias Grosser .release(); 2712ec02acfbSTobias Grosser 2713ec02acfbSTobias Grosser PPCGScop->tagged_dep_order = 2714ec02acfbSTobias Grosser removeUnusedParameters(isl::manage(PPCGScop->tagged_dep_order)) 2715ec02acfbSTobias Grosser .release(); 2716ec02acfbSTobias Grosser } 2717ec02acfbSTobias Grosser 2718e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2719e938517eSTobias Grosser /// 2720f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2721f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2722f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2723f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2724e938517eSTobias Grosser /// 2725e938517eSTobias Grosser /// @returns A new ppcg scop. 2726e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 27279e3db2b7SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 27289e3db2b7SSiddharth Bhat 2729e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2730e938517eSTobias Grosser 2731e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2732a82f2d26SSiddharth Bhat // enable live range reordering 2733a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2734e938517eSTobias Grosser 2735e938517eSTobias Grosser PPCGScop->start = 0; 2736e938517eSTobias Grosser PPCGScop->end = 0; 2737e938517eSTobias Grosser 27388ea1fc19STobias Grosser PPCGScop->context = S->getContext().release(); 273931df6f31STobias Grosser PPCGScop->domain = S->getDomains().release(); 27409e3db2b7SSiddharth Bhat // TODO: investigate this further. PPCG calls collect_call_domains. 27418ea1fc19STobias Grosser PPCGScop->call = isl_union_set_from_set(S->getContext().release()); 2742f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 27435ab39ff2STobias Grosser PPCGScop->reads = S->getReads().release(); 2744e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2745f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 27465ab39ff2STobias Grosser PPCGScop->may_writes = S->getWrites().release(); 2747f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 27485ab39ff2STobias Grosser PPCGScop->must_writes = S->getMustWrites().release(); 2749e938517eSTobias Grosser PPCGScop->live_out = nullptr; 27509e3db2b7SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 27519e3db2b7SSiddharth Bhat PPCGScop->must_kills = KillsInfo.MustKills.take(); 27529e3db2b7SSiddharth Bhat 2753e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2754a82f2d26SSiddharth Bhat PPCGScop->independence = 2755a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2756e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2757e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2758e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2759e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2760e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2761e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2762e938517eSTobias Grosser 276361bd3a48STobias Grosser PPCGScop->schedule = S->getScheduleTree().release(); 2764a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2765a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2766a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2767a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2768a82f2d26SSiddharth Bhat 2769a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2770e938517eSTobias Grosser PPCGScop->pet = nullptr; 2771e938517eSTobias Grosser 2772f384594dSTobias Grosser compute_tagger(PPCGScop); 2773f384594dSTobias Grosser compute_dependences(PPCGScop); 27749e3db2b7SSiddharth Bhat eliminate_dead_code(PPCGScop); 2775ec02acfbSTobias Grosser simplifyPPCGScop(PPCGScop); 2776f384594dSTobias Grosser 2777e938517eSTobias Grosser return PPCGScop; 2778e938517eSTobias Grosser } 2779e938517eSTobias Grosser 2780a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 278160f63b49STobias Grosser /// 278260f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 278360f63b49STobias Grosser /// 278460f63b49STobias Grosser /// @returns A list of array accesses. 278560f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 278660f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 278760f63b49STobias Grosser 278860f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 278960f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 279060f63b49STobias Grosser Access->read = Acc->isRead(); 279160f63b49STobias Grosser Access->write = Acc->isWrite(); 27921515f6b9STobias Grosser Access->access = Acc->getAccessRelation().release(); 279360f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 279460f63b49STobias Grosser Space = isl_space_range(Space); 279560f63b49STobias Grosser Space = isl_space_from_range(Space); 2796fe46c3ffSTobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 279760f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 279860f63b49STobias Grosser Access->tagged_access = 27991515f6b9STobias Grosser isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2800b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 2801fe46c3ffSTobias Grosser Access->ref_id = Acc->getId().release(); 280260f63b49STobias Grosser Access->next = Accesses; 2803b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 280460f63b49STobias Grosser Accesses = Access; 280560f63b49STobias Grosser } 280660f63b49STobias Grosser 280760f63b49STobias Grosser return Accesses; 280860f63b49STobias Grosser } 280960f63b49STobias Grosser 281069b46751STobias Grosser /// Collect the list of GPU statements. 281169b46751STobias Grosser /// 281269b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 281369b46751STobias Grosser /// as well as a list with all memory accesses. 281469b46751STobias Grosser /// 281569b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 281669b46751STobias Grosser /// 281769b46751STobias Grosser /// @returns A linked-list of statements. 281869b46751STobias Grosser gpu_stmt *getStatements() { 281969b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 282069b46751STobias Grosser std::distance(S->begin(), S->end())); 282169b46751STobias Grosser 282269b46751STobias Grosser int i = 0; 282369b46751STobias Grosser for (auto &Stmt : *S) { 282469b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 282569b46751STobias Grosser 2826dcf8d696STobias Grosser GPUStmt->id = Stmt.getDomainId().release(); 282769b46751STobias Grosser 282869b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 282969b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 283060f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 283169b46751STobias Grosser i++; 283269b46751STobias Grosser } 283369b46751STobias Grosser 283469b46751STobias Grosser return Stmts; 283569b46751STobias Grosser } 283669b46751STobias Grosser 283760f63b49STobias Grosser /// Derive the extent of an array. 283860f63b49STobias Grosser /// 2839d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2840d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2841d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2842d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2843d58acf86STobias Grosser /// subscript value for the first dimension. 284460f63b49STobias Grosser /// 284560f63b49STobias Grosser /// @param Array The array to derive the extent for. 284660f63b49STobias Grosser /// 284760f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 2848d2e57981STobias Grosser isl::set getExtent(ScopArrayInfo *Array) { 2849d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 2850fa03cb76STobias Grosser 2851fa03cb76STobias Grosser if (Array->getNumberOfDimensions() == 0) 2852fa03cb76STobias Grosser return isl::set::universe(Array->getSpace()); 2853fa03cb76STobias Grosser 2854fa03cb76STobias Grosser isl::union_map Accesses = S->getAccesses(Array); 2855d2e57981STobias Grosser isl::union_set AccessUSet = Accesses.range(); 2856d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2857d2e57981STobias Grosser AccessUSet = AccessUSet.detect_equalities(); 2858d2e57981STobias Grosser AccessUSet = AccessUSet.coalesce(); 2859d58acf86STobias Grosser 2860d2e57981STobias Grosser if (AccessUSet.is_empty()) 2861d2e57981STobias Grosser return isl::set::empty(Array->getSpace()); 2862d58acf86STobias Grosser 2863d2e57981STobias Grosser isl::set AccessSet = AccessUSet.extract_set(Array->getSpace()); 286460f63b49STobias Grosser 2865d2e57981STobias Grosser isl::local_space LS = isl::local_space(Array->getSpace()); 2866d58acf86STobias Grosser 2867d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0); 2868d2e57981STobias Grosser isl::pw_aff OuterMin = AccessSet.dim_min(0); 2869d2e57981STobias Grosser isl::pw_aff OuterMax = AccessSet.dim_max(0); 2870d2e57981STobias Grosser OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2871d2e57981STobias Grosser OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2872d2e57981STobias Grosser OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2873d2e57981STobias Grosser OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2874d58acf86STobias Grosser 2875d2e57981STobias Grosser isl::set Extent = isl::set::universe(Array->getSpace()); 2876d58acf86STobias Grosser 2877d2e57981STobias Grosser Extent = Extent.intersect(OuterMin.le_set(Val)); 2878d2e57981STobias Grosser Extent = Extent.intersect(OuterMax.ge_set(Val)); 2879d58acf86STobias Grosser 2880d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2881d2e57981STobias Grosser Extent = Extent.lower_bound_si(isl::dim::set, i, 0); 2882d58acf86STobias Grosser 2883b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2884d2e57981STobias Grosser isl::pw_aff PwAff = Array->getDimensionSizePw(i); 2885b7f68b8cSSiddharth Bhat 2886b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2887b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2888d2e57981STobias Grosser if (PwAff.is_null()) { 2889b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2890b7f68b8cSSiddharth Bhat continue; 2891b7f68b8cSSiddharth Bhat } 2892b7f68b8cSSiddharth Bhat 2893d2e57981STobias Grosser isl::pw_aff Val = isl::aff::var_on_domain( 2894d2e57981STobias Grosser isl::local_space(Array->getSpace()), isl::dim::set, i); 2895d2e57981STobias Grosser PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in)); 2896d2e57981STobias Grosser PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in)); 2897d2e57981STobias Grosser isl::set Set = PwAff.gt_set(Val); 2898d2e57981STobias Grosser Extent = Set.intersect(Extent); 2899d58acf86STobias Grosser } 2900d58acf86STobias Grosser 2901d58acf86STobias Grosser return Extent; 290260f63b49STobias Grosser } 290360f63b49STobias Grosser 290460f63b49STobias Grosser /// Derive the bounds of an array. 290560f63b49STobias Grosser /// 290660f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 290760f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 290860f63b49STobias Grosser /// ScopArrayInfo. 290960f63b49STobias Grosser /// 291060f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 291160f63b49STobias Grosser /// @param Array The polly array from which to take the information. 291260f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2913eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> Bounds; 29149e3db2b7SSiddharth Bhat 291560f63b49STobias Grosser if (PPCGArray.n_index > 0) { 291602293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 291702293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 291802293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 291902293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 292002293ed7STobias Grosser isl_set_free(Dom); 29219e3db2b7SSiddharth Bhat isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2922eadf76d3SSiddharth Bhat Bounds.push_back(Zero); 292302293ed7STobias Grosser } else { 292460f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 292560f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 292660f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 292760f63b49STobias Grosser isl_set_free(Dom); 292860f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 292902293ed7STobias Grosser isl_local_space *LS = 293002293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 293160f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 293260f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 293360f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 29348ea1fc19STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext().release()); 2935eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 293660f63b49STobias Grosser } 293702293ed7STobias Grosser } 293860f63b49STobias Grosser 293960f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 294077eef90fSTobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 294160f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 294260f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 294360f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2944eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 294560f63b49STobias Grosser } 29469e3db2b7SSiddharth Bhat 2947eadf76d3SSiddharth Bhat /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2948eadf76d3SSiddharth Bhat /// to have the same parameter dimensions. So, we need to align them to an 2949eadf76d3SSiddharth Bhat /// appropriate space. 2950eadf76d3SSiddharth Bhat /// Scop::Context is _not_ an appropriate space, because when we have 2951eadf76d3SSiddharth Bhat /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 2952eadf76d3SSiddharth Bhat /// contain all parameter dimensions. 2953eadf76d3SSiddharth Bhat /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 2954b65ccc43STobias Grosser isl_space *SeedAlignSpace = S->getParamSpace().release(); 2955eadf76d3SSiddharth Bhat SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 2956eadf76d3SSiddharth Bhat 2957eadf76d3SSiddharth Bhat isl_space *AlignSpace = nullptr; 2958eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AlignedBounds; 2959eadf76d3SSiddharth Bhat std::tie(AlignSpace, AlignedBounds) = 2960eadf76d3SSiddharth Bhat alignPwAffs(std::move(Bounds), SeedAlignSpace); 2961eadf76d3SSiddharth Bhat 2962eadf76d3SSiddharth Bhat assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 2963eadf76d3SSiddharth Bhat 2964eadf76d3SSiddharth Bhat isl_pw_aff_list *BoundsList = 2965eadf76d3SSiddharth Bhat createPwAffList(S->getIslCtx(), std::move(AlignedBounds)); 2966eadf76d3SSiddharth Bhat 29679e3db2b7SSiddharth Bhat isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2968eadf76d3SSiddharth Bhat BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 29699e3db2b7SSiddharth Bhat 29709e3db2b7SSiddharth Bhat assert(BoundsSpace && "Unable to access space of array."); 29719e3db2b7SSiddharth Bhat assert(BoundsList && "Unable to access list of bounds."); 29729e3db2b7SSiddharth Bhat 29739e3db2b7SSiddharth Bhat PPCGArray.bound = 29749e3db2b7SSiddharth Bhat isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 29759e3db2b7SSiddharth Bhat assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 297660f63b49STobias Grosser } 297760f63b49STobias Grosser 297860f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 297960f63b49STobias Grosser /// 298060f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 298143f178bbSSiddharth Bhat void createArrays(gpu_prog *PPCGProg, 298243f178bbSSiddharth Bhat const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 298360f63b49STobias Grosser int i = 0; 298443f178bbSSiddharth Bhat for (auto &Array : ValidSAIs) { 298560f63b49STobias Grosser std::string TypeName; 298660f63b49STobias Grosser raw_string_ostream OS(TypeName); 298760f63b49STobias Grosser 298860f63b49STobias Grosser OS << *Array->getElementType(); 298960f63b49STobias Grosser TypeName = OS.str(); 299060f63b49STobias Grosser 299160f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 299260f63b49STobias Grosser 299377eef90fSTobias Grosser PPCGArray.space = Array->getSpace().release(); 299460f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 299534eeabbcSSiddharth Bhat PPCGArray.size = DL->getTypeAllocSize(Array->getElementType()); 299660f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 299760f63b49STobias Grosser PPCGArray.extent = nullptr; 299860f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 2999d2e57981STobias Grosser PPCGArray.extent = getExtent(Array).release(); 300060f63b49STobias Grosser PPCGArray.n_ref = 0; 300160f63b49STobias Grosser PPCGArray.refs = nullptr; 300260f63b49STobias Grosser PPCGArray.accessed = true; 3003fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 3004fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 300560f63b49STobias Grosser PPCGArray.has_compound_element = false; 300660f63b49STobias Grosser PPCGArray.local = false; 300760f63b49STobias Grosser PPCGArray.declare_local = false; 300860f63b49STobias Grosser PPCGArray.global = false; 300960f63b49STobias Grosser PPCGArray.linearize = false; 301060f63b49STobias Grosser PPCGArray.dep_order = nullptr; 301113c78e4dSTobias Grosser PPCGArray.user = Array; 301260f63b49STobias Grosser 30139e3db2b7SSiddharth Bhat PPCGArray.bound = nullptr; 301460f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 30152d010dafSTobias Grosser i++; 3016b9fc860aSTobias Grosser 3017b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 301860f63b49STobias Grosser } 301960f63b49STobias Grosser } 302060f63b49STobias Grosser 302160f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 302260f63b49STobias Grosser /// 302360f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 302460f63b49STobias Grosser isl_union_map *getArrayIdentity() { 3025b65ccc43STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release()); 302660f63b49STobias Grosser 3027d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 302877eef90fSTobias Grosser isl_space *Space = Array->getSpace().release(); 302960f63b49STobias Grosser Space = isl_space_map_from_set(Space); 303060f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 303160f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 303260f63b49STobias Grosser } 303360f63b49STobias Grosser 303460f63b49STobias Grosser return Maps; 303560f63b49STobias Grosser } 303660f63b49STobias Grosser 3037e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 3038e938517eSTobias Grosser /// 3039a6d48f59SMichael Kruse /// @returns A new gpu program description. 3040e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 3041e938517eSTobias Grosser 3042e938517eSTobias Grosser if (!PPCGScop) 3043e938517eSTobias Grosser return nullptr; 3044e938517eSTobias Grosser 3045e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 3046e938517eSTobias Grosser 3047e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 3048e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 3049aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 305060f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 305160f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 305260f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 305360f63b49STobias Grosser PPCGProg->tagged_must_kill = 305460f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 305560f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 305660f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 30579e3db2b7SSiddharth Bhat // TODO: verify that this assignment is correct. 3058e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 3059a82f2d26SSiddharth Bhat 3060a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 3061a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 3062a82f2d26SSiddharth Bhat // what the semantics of this is. 3063a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 3064a82f2d26SSiddharth Bhat PPCGProg->array_order = 3065a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 306669b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 306769b46751STobias Grosser PPCGProg->stmts = getStatements(); 306843f178bbSSiddharth Bhat 306943f178bbSSiddharth Bhat // Only consider arrays that have a non-empty extent. 307043f178bbSSiddharth Bhat // Otherwise, this will cause us to consider the following kinds of 307143f178bbSSiddharth Bhat // empty arrays: 307243f178bbSSiddharth Bhat // 1. Invariant loads that are represented by SAI objects. 307343f178bbSSiddharth Bhat // 2. Arrays with statically known zero size. 307443f178bbSSiddharth Bhat auto ValidSAIsRange = 307543f178bbSSiddharth Bhat make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 3076d2e57981STobias Grosser return !getExtent(SAI).is_empty(); 307743f178bbSSiddharth Bhat }); 307843f178bbSSiddharth Bhat SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 307943f178bbSSiddharth Bhat ValidSAIsRange.end()); 308043f178bbSSiddharth Bhat 308143f178bbSSiddharth Bhat PPCGProg->n_array = 308243f178bbSSiddharth Bhat ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 308360f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 308460f63b49STobias Grosser PPCGProg->n_array); 308560f63b49STobias Grosser 308643f178bbSSiddharth Bhat createArrays(PPCGProg, ValidSAIs); 3087e938517eSTobias Grosser 3088d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 3089e938517eSTobias Grosser return PPCGProg; 3090e938517eSTobias Grosser } 3091e938517eSTobias Grosser 309269b46751STobias Grosser struct PrintGPUUserData { 309369b46751STobias Grosser struct cuda_info *CudaInfo; 309469b46751STobias Grosser struct gpu_prog *PPCGProg; 309569b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 309669b46751STobias Grosser }; 309769b46751STobias Grosser 309869b46751STobias Grosser /// Print a user statement node in the host code. 309969b46751STobias Grosser /// 310069b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 310169b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 310269b46751STobias Grosser /// host ast. 310369b46751STobias Grosser /// 310469b46751STobias Grosser /// @param P The printer to print to 310569b46751STobias Grosser /// @param Options The printing options to use 310669b46751STobias Grosser /// @param Node The node to print 310769b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 310869b46751STobias Grosser /// expected to be of type PrintGPUUserData. 310969b46751STobias Grosser /// 311069b46751STobias Grosser /// @returns A printer to which the output has been printed. 311169b46751STobias Grosser static __isl_give isl_printer * 311269b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 311369b46751STobias Grosser __isl_take isl_ast_print_options *Options, 311469b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 311569b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 311669b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 311769b46751STobias Grosser 311869b46751STobias Grosser if (Id) { 311920251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 312020251734STobias Grosser 312120251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 312220251734STobias Grosser // otherwise try to call pet functionality that is not available in 312320251734STobias Grosser // Polly. 312420251734STobias Grosser if (IsUser) { 312520251734STobias Grosser P = isl_printer_start_line(P); 312620251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 312720251734STobias Grosser P = isl_printer_end_line(P); 312820251734STobias Grosser isl_id_free(Id); 312920251734STobias Grosser isl_ast_print_options_free(Options); 313020251734STobias Grosser return P; 313120251734STobias Grosser } 313220251734STobias Grosser 313369b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 313469b46751STobias Grosser isl_id_free(Id); 313569b46751STobias Grosser Data->Kernels.push_back(Kernel); 313669b46751STobias Grosser } 313769b46751STobias Grosser 313869b46751STobias Grosser return print_host_user(P, Options, Node, User); 313969b46751STobias Grosser } 314069b46751STobias Grosser 314169b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 314269b46751STobias Grosser /// 314369b46751STobias Grosser /// @param Kernel The kernel to print 314469b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 314569b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 314669b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 314769b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 314869b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 314969b46751STobias Grosser char *String = isl_printer_get_str(P); 315069b46751STobias Grosser printf("%s\n", String); 315169b46751STobias Grosser free(String); 315269b46751STobias Grosser isl_printer_free(P); 315369b46751STobias Grosser } 315469b46751STobias Grosser 315569b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 315669b46751STobias Grosser /// 315769b46751STobias Grosser /// @param Tree An AST describing GPU code 315869b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 315969b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 316069b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 316169b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 316269b46751STobias Grosser 316369b46751STobias Grosser PrintGPUUserData Data; 316469b46751STobias Grosser Data.PPCGProg = PPCGProg; 316569b46751STobias Grosser 316669b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 316769b46751STobias Grosser Options = 316869b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 316969b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 317069b46751STobias Grosser char *String = isl_printer_get_str(P); 317169b46751STobias Grosser printf("# host\n"); 317269b46751STobias Grosser printf("%s\n", String); 317369b46751STobias Grosser free(String); 317469b46751STobias Grosser isl_printer_free(P); 317569b46751STobias Grosser 317669b46751STobias Grosser for (auto Kernel : Data.Kernels) { 317769b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 317869b46751STobias Grosser printKernel(Kernel); 317969b46751STobias Grosser } 318069b46751STobias Grosser } 318169b46751STobias Grosser 3182f384594dSTobias Grosser // Generate a GPU program using PPCG. 3183f384594dSTobias Grosser // 3184f384594dSTobias Grosser // GPU mapping consists of multiple steps: 3185f384594dSTobias Grosser // 3186f384594dSTobias Grosser // 1) Compute new schedule for the program. 3187f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 3188f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 3189f384594dSTobias Grosser // 3190f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3191f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3192f384594dSTobias Grosser // strategy directly from this pass. 3193f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3194f384594dSTobias Grosser 3195f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 3196f384594dSTobias Grosser 3197f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 3198f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 3199f384594dSTobias Grosser PPCGGen->print = nullptr; 3200f384594dSTobias Grosser PPCGGen->print_user = nullptr; 320160c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3202f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 3203f384594dSTobias Grosser PPCGGen->tree = nullptr; 3204f384594dSTobias Grosser PPCGGen->types.n = 0; 3205f384594dSTobias Grosser PPCGGen->types.name = nullptr; 3206f384594dSTobias Grosser PPCGGen->sizes = nullptr; 3207f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 3208f384594dSTobias Grosser PPCGGen->kernel_id = 0; 3209f384594dSTobias Grosser 3210f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 3211f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3212f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 32132341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3214f384594dSTobias Grosser 3215f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 3216f384594dSTobias Grosser 3217ec02acfbSTobias Grosser /// Copy to and from device functions may introduce new parameters, which 3218ec02acfbSTobias Grosser /// must be present in the schedule tree root for code generation. Hence, 3219ec02acfbSTobias Grosser /// we ensure that all possible parameters are introduced from this point. 3220ec02acfbSTobias Grosser if (!PollyManagedMemory) 3221b5563c68STobias Grosser Schedule = 3222b5563c68STobias Grosser isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3223b5563c68STobias Grosser 3224ec02acfbSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 3225ec02acfbSTobias Grosser 322669b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 3227aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 3228638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3229638316daSSiddharth Bhat << " does not have permutable bands. Bailing out\n";); 323069b46751STobias Grosser } else { 3231861a387fSTobias Grosser const bool CreateTransferToFromDevice = !PollyManagedMemory; 3232861a387fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice); 323369b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 323469b46751STobias Grosser } 3235aef5196fSTobias Grosser 3236f384594dSTobias Grosser if (DumpSchedule) { 3237f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 3238f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3239f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 3240f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 3241f384594dSTobias Grosser if (Schedule) 3242f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 3243f384594dSTobias Grosser else 3244f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 3245f384594dSTobias Grosser 3246f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 3247f384594dSTobias Grosser isl_printer_free(P); 3248f384594dSTobias Grosser } 3249f384594dSTobias Grosser 325069b46751STobias Grosser if (DumpCode) { 325169b46751STobias Grosser printf("Code\n"); 325269b46751STobias Grosser printf("====\n"); 325369b46751STobias Grosser if (PPCGGen->tree) 325469b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 325569b46751STobias Grosser else 325669b46751STobias Grosser printf("No code generated\n"); 325769b46751STobias Grosser } 325869b46751STobias Grosser 3259f384594dSTobias Grosser isl_schedule_free(Schedule); 3260f384594dSTobias Grosser 3261f384594dSTobias Grosser return PPCGGen; 3262f384594dSTobias Grosser } 3263f384594dSTobias Grosser 3264f384594dSTobias Grosser /// Free gpu_gen structure. 3265f384594dSTobias Grosser /// 3266f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 3267f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 3268f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 3269f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 3270f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 3271f384594dSTobias Grosser free(PPCGGen); 3272f384594dSTobias Grosser } 3273f384594dSTobias Grosser 3274b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 3275b307ed4dSTobias Grosser /// 3276b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 3277b307ed4dSTobias Grosser /// ourselves. 3278b307ed4dSTobias Grosser /// 3279b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 3280b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 3281b307ed4dSTobias Grosser free(PPCGScop->options->debug); 3282b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 3283b307ed4dSTobias Grosser free(PPCGScop->options); 3284b307ed4dSTobias Grosser PPCGScop->options = nullptr; 3285b307ed4dSTobias Grosser } 3286b307ed4dSTobias Grosser 328782f2af35STobias Grosser /// Approximate the number of points in the set. 328882f2af35STobias Grosser /// 328982f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 329082f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 329182f2af35STobias Grosser /// 329282f2af35STobias Grosser /// @param Set The set to count. 329382f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 329482f2af35STobias Grosser /// expression. 329582f2af35STobias Grosser /// 329682f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 329782f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 329882f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 329982f2af35STobias Grosser 330082f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 330182f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 330282f2af35STobias Grosser 330382f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 330482f2af35STobias Grosser Space = isl_space_params(Space); 330582f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 330682f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 330782f2af35STobias Grosser 330882f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 330982f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 331082f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 331182f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 331282f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 331382f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 331482f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 331582f2af35STobias Grosser } 331682f2af35STobias Grosser 331782f2af35STobias Grosser isl_set_free(Set); 331882f2af35STobias Grosser isl_pw_aff_free(OneAff); 331982f2af35STobias Grosser 332082f2af35STobias Grosser return Expr; 332182f2af35STobias Grosser } 332282f2af35STobias Grosser 332382f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 332482f2af35STobias Grosser /// statement. 332582f2af35STobias Grosser /// 332682f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 332782f2af35STobias Grosser /// instructions. 332882f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 332982f2af35STobias Grosser /// expression. 333082f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 333182f2af35STobias Grosser /// by @p Stmt. 333282f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 333382f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 3334dcf8d696STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 333582f2af35STobias Grosser 333682f2af35STobias Grosser long InstCount = 0; 333782f2af35STobias Grosser 333882f2af35STobias Grosser if (Stmt.isBlockStmt()) { 333982f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 334082f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 334182f2af35STobias Grosser } else { 334282f2af35STobias Grosser auto *R = Stmt.getRegion(); 334382f2af35STobias Grosser 334482f2af35STobias Grosser for (auto *BB : R->blocks()) { 334582f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 334682f2af35STobias Grosser } 334782f2af35STobias Grosser } 334882f2af35STobias Grosser 334982f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 335082f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 335182f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 335282f2af35STobias Grosser } 335382f2af35STobias Grosser 335482f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 335582f2af35STobias Grosser /// 335682f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 335782f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 335882f2af35STobias Grosser /// expression. 335982f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 336082f2af35STobias Grosser /// in @p S. 336182f2af35STobias Grosser __isl_give isl_ast_expr * 336282f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 336382f2af35STobias Grosser isl_ast_expr *Instructions; 336482f2af35STobias Grosser 336582f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 336682f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 336782f2af35STobias Grosser 336882f2af35STobias Grosser for (ScopStmt &Stmt : S) { 336982f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 337082f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 337182f2af35STobias Grosser } 337282f2af35STobias Grosser return Instructions; 337382f2af35STobias Grosser } 337482f2af35STobias Grosser 337582f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 337682f2af35STobias Grosser /// 337782f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 337882f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 337982f2af35STobias Grosser /// expression. 338082f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 338182f2af35STobias Grosser /// compute and to FALSE, otherwise. 338282f2af35STobias Grosser __isl_give isl_ast_expr * 338382f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 338482f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 338582f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 338682f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 338782f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 338882f2af35STobias Grosser } 338982f2af35STobias Grosser 3390f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 3391f291c8d5SSiddharth Bhat /// kernels. 3392f291c8d5SSiddharth Bhat /// 3393f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 3394f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 33958fc6cdfbSTobias Grosser bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 33968fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 3397f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 3398f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 33998fc6cdfbSTobias Grosser if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 34008fc6cdfbSTobias Grosser AllowCUDALibDevice)) { 3401f291c8d5SSiddharth Bhat continue; 3402f291c8d5SSiddharth Bhat } 3403f291c8d5SSiddharth Bhat 3404bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 3405bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3406bccaea57SSiddharth Bhat if (!p) 3407bccaea57SSiddharth Bhat continue; 3408bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 3409bccaea57SSiddharth Bhat return true; 3410bccaea57SSiddharth Bhat } 3411f291c8d5SSiddharth Bhat } 3412bccaea57SSiddharth Bhat return false; 3413bccaea57SSiddharth Bhat } 3414bccaea57SSiddharth Bhat 3415f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 34168fc6cdfbSTobias Grosser bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3417bccaea57SSiddharth Bhat for (auto &Stmt : S) { 3418bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 34198fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 34208fc6cdfbSTobias Grosser AllowCUDALibDevice)) 3421bccaea57SSiddharth Bhat return true; 3422bccaea57SSiddharth Bhat } else { 3423bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 3424bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 3425bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 34268fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3427bccaea57SSiddharth Bhat return true; 3428bccaea57SSiddharth Bhat } 3429bccaea57SSiddharth Bhat } 3430bccaea57SSiddharth Bhat return false; 3431bccaea57SSiddharth Bhat } 3432bccaea57SSiddharth Bhat 343338fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 343438fc0aedSTobias Grosser /// 343532837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 343632837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 343732837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 343838fc0aedSTobias Grosser ScopAnnotator Annotator; 343938fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 344038fc0aedSTobias Grosser 344138fc0aedSTobias Grosser Region *R = &S->getRegion(); 344238fc0aedSTobias Grosser 344338fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 344438fc0aedSTobias Grosser 344538fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 344638fc0aedSTobias Grosser 344738fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 344838fc0aedSTobias Grosser 344938fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 345038fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 345138fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 345238fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 345338fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 345438fc0aedSTobias Grosser // code generating this scop. 345503346c27SSiddharth Bhat BBPair StartExitBlocks; 345603346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 345703346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 34582d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3459256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 346038fc0aedSTobias Grosser 346103346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 346203346c27SSiddharth Bhat 34632d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 346417f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 3465acf80064SEli Friedman 346638fc0aedSTobias Grosser // TODO: Handle LICM 346738fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 346838fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 3469cb1aef8dSTobias Grosser 3470cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 34712b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 347282f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 347382f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 3474cb1aef8dSTobias Grosser isl_ast_build_free(Build); 3475cb1aef8dSTobias Grosser 34769e3db2b7SSiddharth Bhat // preload invariant loads. Note: This should happen before the RTC 34779e3db2b7SSiddharth Bhat // because the RTC may depend on values that are invariant load hoisted. 347871dfb3ebSSiddharth Bhat if (!NodeBuilder.preloadInvariantLoads()) { 347971dfb3ebSSiddharth Bhat DEBUG(dbgs() << "preloading invariant loads failed in function: " + 34804ebeb356SSiddharth Bhat S->getFunction().getName() + 34814ebeb356SSiddharth Bhat " | Scop Region: " + S->getNameStr()); 348271dfb3ebSSiddharth Bhat // adjust the dominator tree accordingly. 348371dfb3ebSSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 348471dfb3ebSSiddharth Bhat assert(ExitingBlock); 348571dfb3ebSSiddharth Bhat auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 348671dfb3ebSSiddharth Bhat assert(MergeBlock); 348771dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*StartBlock, Builder); 348871dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*ExitingBlock, Builder); 348971dfb3ebSSiddharth Bhat auto *ExitingBB = S->getExitingBlock(); 349071dfb3ebSSiddharth Bhat assert(ExitingBB); 34919e3db2b7SSiddharth Bhat 349271dfb3ebSSiddharth Bhat DT->changeImmediateDominator(MergeBlock, ExitingBB); 349371dfb3ebSSiddharth Bhat DT->eraseNode(ExitingBlock); 349471dfb3ebSSiddharth Bhat isl_ast_expr_free(Condition); 349571dfb3ebSSiddharth Bhat isl_ast_node_free(Root); 349671dfb3ebSSiddharth Bhat } else { 349771dfb3ebSSiddharth Bhat 349871dfb3ebSSiddharth Bhat NodeBuilder.addParameters(S->getContext().release()); 3499cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 3500cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3501cb1aef8dSTobias Grosser 350238fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 3503fa7b0802STobias Grosser 350438fc0aedSTobias Grosser NodeBuilder.create(Root); 350571dfb3ebSSiddharth Bhat } 35065857b701STobias Grosser 3507bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 3508bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3509de244eb4STobias Grosser /// point in running it on a GPU. 3510bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 351103346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 3512bc653f20STobias Grosser 35135857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 351403346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 351538fc0aedSTobias Grosser } 351638fc0aedSTobias Grosser 3517e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 3518e938517eSTobias Grosser S = &CurrentScop; 351938fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 352038fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 352138fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 35227b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 352338fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3524e938517eSTobias Grosser 3525656e6295SSiddharth Bhat DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S) 3526656e6295SSiddharth Bhat << " | loop depth: " << S->getMaxLoopDepth() << "\n"); 3527656e6295SSiddharth Bhat 3528f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 3529f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 3530f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 3531bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 3532bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 35338fc6cdfbSTobias Grosser if (containsInvalidKernelFunction(CurrentScop, 35348fc6cdfbSTobias Grosser Architecture == GPUArch::NVPTX64)) { 3535f291c8d5SSiddharth Bhat DEBUG( 3536638316daSSiddharth Bhat dbgs() << getUniqueScopName(S) 3537638316daSSiddharth Bhat << " contains function which cannot be materialised in a GPU " 3538f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3539bccaea57SSiddharth Bhat return false; 3540f291c8d5SSiddharth Bhat } 3541bccaea57SSiddharth Bhat 3542e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3543e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3544f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 354538fc0aedSTobias Grosser 354602ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 354732837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 354802ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 3549638316daSSiddharth Bhat } else { 3550638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3551638316daSSiddharth Bhat << " has empty PPCGGen->tree. Bailing out.\n"); 355202ca346eSSingapuram Sanjay Srivallabh } 355338fc0aedSTobias Grosser 3554b307ed4dSTobias Grosser freeOptions(PPCGScop); 3555f384594dSTobias Grosser freePPCGGen(PPCGGen); 3556e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3557e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3558e938517eSTobias Grosser 3559e938517eSTobias Grosser return true; 3560e938517eSTobias Grosser } 35619dfe4e7cSTobias Grosser 35629dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 35639dfe4e7cSTobias Grosser 35649dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 35659dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 35669dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 35679dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 35685cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 35699dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 35709dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 35719dfe4e7cSTobias Grosser 35729dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 35739dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 35749dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 35759dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 35769dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 35775cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 35789dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 35799dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 35809dfe4e7cSTobias Grosser 35819dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 35829dfe4e7cSTobias Grosser // region tree. 35839dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 35849dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 35859dfe4e7cSTobias Grosser } 35869dfe4e7cSTobias Grosser }; 358724222c73STobias Grosser } // namespace 35889dfe4e7cSTobias Grosser 35899dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 35909dfe4e7cSTobias Grosser 359117f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 359217f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 359317f01968SSiddharth Bhat generator->Runtime = Runtime; 359417f01968SSiddharth Bhat generator->Architecture = Arch; 359517f01968SSiddharth Bhat return generator; 359617f01968SSiddharth Bhat } 35979dfe4e7cSTobias Grosser 35989dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 35999dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 36009dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 36019dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 36029dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 36039dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 36049dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 36055cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 36069dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 36079dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3608