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 93*c4a4af47SSiddharth Bhat bool polly::PollyManagedMemory; 94*c4a4af47SSiddharth Bhat static cl::opt<bool, true> 95*c4a4af47SSiddharth 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"), 99*c4a4af47SSiddharth Bhat cl::location(PollyManagedMemory), cl::Hidden, 100*c4a4af47SSiddharth 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 291edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 29235de9009SSiddharth Bhat isl::map AddrFunc = Acc->getAddressFunction(); 293dcf8d696STobias Grosser AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain()); 29435de9009SSiddharth Bhat 29535de9009SSiddharth Bhat isl::id RefId = Acc->getId(); 29635de9009SSiddharth Bhat isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 29735de9009SSiddharth Bhat 29835de9009SSiddharth Bhat isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 29935de9009SSiddharth Bhat MPA = MPA.coalesce(); 30035de9009SSiddharth Bhat MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 30135de9009SSiddharth Bhat 30235de9009SSiddharth Bhat isl::ast_expr Access = Build.access_from(MPA); 30335de9009SSiddharth Bhat Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 30435de9009SSiddharth Bhat RefToExpr = RefToExpr.set(RefId, Access); 305edb885cbSTobias Grosser } 306edb885cbSTobias Grosser 30735de9009SSiddharth Bhat return RefToExpr.release(); 30860c60025STobias Grosser } 309f384594dSTobias Grosser 310a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 311a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 312a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 313a90be207SSiddharth Bhat if (bytes == 0) 314a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 315a90be207SSiddharth Bhat return bytes; 316a90be207SSiddharth Bhat } 317a90be207SSiddharth Bhat 31838fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 31938fc0aedSTobias Grosser /// 32038fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 321a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 32238fc0aedSTobias Grosser /// for generating GPU specific user nodes. 32338fc0aedSTobias Grosser /// 32438fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 32538fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 32638fc0aedSTobias Grosser public: 3272d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 32838fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 329acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 33017f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3312d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 33217f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 333edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 334edb885cbSTobias Grosser } 33538fc0aedSTobias Grosser 336fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 337fa7b0802STobias Grosser void initializeAfterRTH(); 338fa7b0802STobias Grosser 339fa7b0802STobias Grosser /// Finalize the generated scop. 340fa7b0802STobias Grosser virtual void finalize(); 341fa7b0802STobias Grosser 3425857b701STobias Grosser /// Track if the full build process was successful. 3435857b701STobias Grosser /// 3445857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3455857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3465857b701STobias Grosser bool BuildSuccessful = true; 3475857b701STobias Grosser 348bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 349bc653f20STobias Grosser unsigned DeepestSequential = 0; 350bc653f20STobias Grosser 351bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 352bc653f20STobias Grosser unsigned DeepestParallel = 0; 353bc653f20STobias Grosser 35479f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 35579f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 35679f13b9aSSingapuram Sanjay Srivallabh 35738fc0aedSTobias Grosser private: 35874dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 35974dc3cb4STobias Grosser /// 36074dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 36174dc3cb4STobias Grosser /// more. 36274dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 36374dc3cb4STobias Grosser 36413c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 36513c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3667287aeddSTobias Grosser 367fa7b0802STobias Grosser /// The current GPU context. 368fa7b0802STobias Grosser Value *GPUContext; 369fa7b0802STobias Grosser 370b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 371b513b491STobias Grosser std::vector<isl_id *> KernelIds; 372b513b491STobias Grosser 37332837fe3STobias Grosser /// A module containing GPU code. 37432837fe3STobias Grosser /// 37532837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 37632837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 37732837fe3STobias Grosser 37832837fe3STobias Grosser /// The GPU program we generate code for. 37932837fe3STobias Grosser gpu_prog *Prog; 38032837fe3STobias Grosser 38117f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 38217f01968SSiddharth Bhat GPURuntime Runtime; 38317f01968SSiddharth Bhat 38417f01968SSiddharth Bhat /// The GPU Architecture to target. 38517f01968SSiddharth Bhat GPUArch Arch; 38617f01968SSiddharth Bhat 387472f9654STobias Grosser /// Class to free isl_ids. 388472f9654STobias Grosser class IslIdDeleter { 389472f9654STobias Grosser public: 390472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 391472f9654STobias Grosser }; 392472f9654STobias Grosser 393472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 394472f9654STobias Grosser /// 395472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 396472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 397472f9654STobias Grosser 398edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 399edb885cbSTobias Grosser 40038fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 40138fc0aedSTobias Grosser /// 40238fc0aedSTobias Grosser /// These AST nodes can be of type: 40338fc0aedSTobias Grosser /// 40438fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 40538fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 40613c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 4075260c041STobias Grosser /// - In-kernel synchronization 4085260c041STobias Grosser /// - In-kernel memory copy statement 40938fc0aedSTobias Grosser /// 4101fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 4111fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 41232837fe3STobias Grosser 41313c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 41413c78e4dSTobias Grosser 41513c78e4dSTobias Grosser /// Create code for a data transfer statement 41613c78e4dSTobias Grosser /// 41713c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 41813c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 41913c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 42013c78e4dSTobias Grosser enum DataDirection Direction); 42113c78e4dSTobias Grosser 422edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 423edb885cbSTobias Grosser /// 424edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 425edb885cbSTobias Grosser /// 426e53c924bSSiddharth Bhat /// @returns A tuple, whose: 427e53c924bSSiddharth Bhat /// - First element contains the set of values referenced by the 428e53c924bSSiddharth Bhat /// kernel 429e53c924bSSiddharth Bhat /// - Second element contains the set of functions referenced by the 430e53c924bSSiddharth Bhat /// kernel. All functions in the set satisfy 431e53c924bSSiddharth Bhat /// `isValidFunctionInKernel`. 432e53c924bSSiddharth Bhat /// - Third element contains loops that have induction variables 433e53c924bSSiddharth Bhat /// which are used in the kernel, *and* these loops are *neither* 434e53c924bSSiddharth Bhat /// in the scop, nor do they immediately surroung the Scop. 435e53c924bSSiddharth Bhat /// See [Code generation of induction variables of loops outside 436e53c924bSSiddharth Bhat /// Scops] 437e53c924bSSiddharth Bhat std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>> 438f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 439edb885cbSTobias Grosser 44079a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 44179a947c2STobias Grosser /// 44279a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 44379a947c2STobias Grosser /// 44479a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 44579a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 44679a947c2STobias Grosser 447b99c1171STobias Grosser /// Get the managed array pointer for sending host pointers to the device. 448abed4969SSiddharth Bhat /// \note 449abed4969SSiddharth Bhat /// This is to be used only with managed memory 450b99c1171STobias Grosser Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo); 451abed4969SSiddharth Bhat 45279a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 45379a947c2STobias Grosser /// 45479a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 45579a947c2STobias Grosser /// 45679a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 45779a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 45879a947c2STobias Grosser 459a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 460a90be207SSiddharth Bhat /// parameters. 461a90be207SSiddharth Bhat /// 462a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 463a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 464a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 465a90be207SSiddharth Bhat /// parameter. 466a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 467a90be207SSiddharth Bhat int Index); 468a90be207SSiddharth Bhat 46979a947c2STobias Grosser /// Create kernel launch parameters. 47079a947c2STobias Grosser /// 47179a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 47279a947c2STobias Grosser /// @param F The kernel function that has been created. 47357693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 47479a947c2STobias Grosser /// 47579a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 47679a947c2STobias Grosser /// values that are passed to the kernel. 47757693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 47857693272STobias Grosser SetVector<Value *> SubtreeValues); 47979a947c2STobias Grosser 480b513b491STobias Grosser /// Create declarations for kernel variable. 481b513b491STobias Grosser /// 482b513b491STobias Grosser /// This includes shared memory declarations. 483b513b491STobias Grosser /// 484b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 485b513b491STobias Grosser /// @param FN The function into which to generate the variables. 486b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 487b513b491STobias Grosser 488c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 489c1c6a2a6STobias Grosser /// 490c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 491c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 492c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 493c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 494c1c6a2a6STobias Grosser /// as specified here. 495c1c6a2a6STobias Grosser /// 496c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 497c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 498c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 499c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 500c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 501c1c6a2a6STobias Grosser Value *BlockDimZ); 502c1c6a2a6STobias Grosser 50332837fe3STobias Grosser /// Create GPU kernel. 50432837fe3STobias Grosser /// 50532837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 50632837fe3STobias Grosser /// 50732837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 50832837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 50932837fe3STobias Grosser 51013c78e4dSTobias Grosser /// Generate code that computes the size of an array. 51113c78e4dSTobias Grosser /// 51213c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 51313c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 51413c78e4dSTobias Grosser 515aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 516aaabbbf8STobias Grosser /// 517aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 518aaabbbf8STobias Grosser /// 519aaabbbf8STobias Grosser /// Example: 520aaabbbf8STobias Grosser /// 521aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 522aaabbbf8STobias Grosser /// A[i + 42] += ... 523aaabbbf8STobias Grosser /// 524aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 525aaabbbf8STobias Grosser /// 526aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 527aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 528aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 529aaabbbf8STobias Grosser 53000bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 53100bb5a99STobias Grosser /// 53200bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 53300bb5a99STobias Grosser /// @param FN The function created for the kernel. 53400bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 53500bb5a99STobias Grosser 53632837fe3STobias Grosser /// Create kernel function. 53732837fe3STobias Grosser /// 53832837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 53932837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 54032837fe3STobias Grosser /// start block of this newly created function. 54132837fe3STobias Grosser /// 54232837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 543edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 544f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 545f291c8d5SSiddharth Bhat /// kernel. 546edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 547f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 548f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 54932837fe3STobias Grosser 55032837fe3STobias Grosser /// Create the declaration of a kernel function. 55132837fe3STobias Grosser /// 55232837fe3STobias Grosser /// The kernel function takes as arguments: 55332837fe3STobias Grosser /// 55432837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 555f6044bd0STobias Grosser /// - Host iterators 556c84a1995STobias Grosser /// - Parameters 55732837fe3STobias Grosser /// - Other LLVM Value references (TODO) 55832837fe3STobias Grosser /// 55932837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 560edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 561edb885cbSTobias Grosser /// 56232837fe3STobias Grosser /// @returns The newly declared function. 563edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 564edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 56532837fe3STobias Grosser 566472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 567472f9654STobias Grosser /// 568472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 569472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 570472f9654STobias Grosser 5712f3073b5SPhilipp Schaad /// Insert function calls to retrieve the SPIR group/local ids. 5722f3073b5SPhilipp Schaad /// 5732f3073b5SPhilipp Schaad /// @param The kernel to generate the function calls for. 5742f3073b5SPhilipp Schaad void insertKernelCallsSPIR(ppcg_kernel *Kernel); 5752f3073b5SPhilipp Schaad 576f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 577f291c8d5SSiddharth Bhat /// 578f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 579f291c8d5SSiddharth Bhat /// SubtreeFunctions. 580f291c8d5SSiddharth Bhat /// 581f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 582f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 583f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 584f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 585f291c8d5SSiddharth Bhat /// 586f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 587f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 588f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 589f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 590f291c8d5SSiddharth Bhat /// 591f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 592f291c8d5SSiddharth Bhat /// this kernel. 593f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 594f291c8d5SSiddharth Bhat 595b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 596b513b491STobias Grosser /// 597b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 598b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 599b513b491STobias Grosser 600edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 601edb885cbSTobias Grosser /// 602edb885cbSTobias Grosser /// @param Expr The expression containing the call. 603edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 604edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 605edb885cbSTobias Grosser 6065260c041STobias Grosser /// Create an in-kernel synchronization call. 6075260c041STobias Grosser void createKernelSync(); 6085260c041STobias Grosser 60974dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 61074dc3cb4STobias Grosser /// 61174dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 61274dc3cb4STobias Grosser std::string createKernelASM(); 61374dc3cb4STobias Grosser 61474dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 61574dc3cb4STobias Grosser /// 61674dc3cb4STobias Grosser /// @param F The function to remove references to. 61774dc3cb4STobias Grosser void clearDominators(Function *F); 61874dc3cb4STobias Grosser 61974dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 62074dc3cb4STobias Grosser /// 62174dc3cb4STobias Grosser /// @param F The function to remove references to. 62274dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 62374dc3cb4STobias Grosser 62474dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 62574dc3cb4STobias Grosser /// 62674dc3cb4STobias Grosser /// @param F The function to remove references to. 62774dc3cb4STobias Grosser void clearLoops(Function *F); 62874dc3cb4STobias Grosser 6298fc6cdfbSTobias Grosser /// Check if the scop requires to be linked with CUDA's libdevice. 6308fc6cdfbSTobias Grosser bool requiresCUDALibDevice(); 6318fc6cdfbSTobias Grosser 6328fc6cdfbSTobias Grosser /// Link with the NVIDIA libdevice library (if needed and available). 6338fc6cdfbSTobias Grosser void addCUDALibDevice(); 6348fc6cdfbSTobias Grosser 63532837fe3STobias Grosser /// Finalize the generation of the kernel function. 63632837fe3STobias Grosser /// 63732837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 63832837fe3STobias Grosser /// dump its IR to stderr. 63957793596STobias Grosser /// 64057793596STobias Grosser /// @returns The Assembly string of the kernel. 64157793596STobias Grosser std::string finalizeKernelFunction(); 642fa7b0802STobias Grosser 64351dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 64451dfc275STobias Grosser /// 64551dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 646a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 64751dfc275STobias Grosser /// the kernel terminates. 64851dfc275STobias Grosser /// 64951dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 65051dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 65151dfc275STobias Grosser 6527287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 653fa7b0802STobias Grosser void allocateDeviceArrays(); 654fa7b0802STobias Grosser 655b99c1171STobias Grosser /// Create code to prepare the managed device pointers. 656b99c1171STobias Grosser void prepareManagedDeviceArrays(); 657b99c1171STobias Grosser 6587287aeddSTobias Grosser /// Free all allocated device arrays. 6597287aeddSTobias Grosser void freeDeviceArrays(); 6607287aeddSTobias Grosser 661fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 662fa7b0802STobias Grosser /// 663fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 664fa7b0802STobias Grosser Value *createCallInitContext(); 665fa7b0802STobias Grosser 66679a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 66779a947c2STobias Grosser /// 66879a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 66979a947c2STobias Grosser /// 67079a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 67179a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 67279a947c2STobias Grosser 673fa7b0802STobias Grosser /// Create a call to free the GPU context. 674fa7b0802STobias Grosser /// 675fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 676fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 677fa7b0802STobias Grosser 6787287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6797287aeddSTobias Grosser /// 6807287aeddSTobias Grosser /// @param Size The size of memory to allocate 6817287aeddSTobias Grosser /// 6827287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 683fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6847287aeddSTobias Grosser 6857287aeddSTobias Grosser /// Create a call to free a device array. 6867287aeddSTobias Grosser /// 6877287aeddSTobias Grosser /// @param Array The device array to free. 6887287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 68913c78e4dSTobias Grosser 69013c78e4dSTobias Grosser /// Create a call to copy data from host to device. 69113c78e4dSTobias Grosser /// 69213c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 69313c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 69413c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 69513c78e4dSTobias Grosser Value *Size); 69613c78e4dSTobias Grosser 69713c78e4dSTobias Grosser /// Create a call to copy data from device to host. 69813c78e4dSTobias Grosser /// 69913c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 70013c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 70113c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 70213c78e4dSTobias Grosser Value *Size); 70357793596STobias Grosser 704abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 705abed4969SSiddharth Bhat /// \note 706abed4969SSiddharth Bhat /// This is to be used only with managed memory. 707abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 708abed4969SSiddharth Bhat 70957793596STobias Grosser /// Create a call to get a kernel from an assembly string. 71057793596STobias Grosser /// 71157793596STobias Grosser /// @param Buffer The string describing the kernel. 71257793596STobias Grosser /// @param Entry The name of the kernel function to call. 71357793596STobias Grosser /// 71457793596STobias Grosser /// @returns A pointer to a kernel object 71557793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 71657793596STobias Grosser 71757793596STobias Grosser /// Create a call to free a GPU kernel. 71857793596STobias Grosser /// 71957793596STobias Grosser /// @param GPUKernel THe kernel to free. 72057793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 72179a947c2STobias Grosser 72279a947c2STobias Grosser /// Create a call to launch a GPU kernel. 72379a947c2STobias Grosser /// 72479a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 72579a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 72679a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 72779a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 72879a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 72979a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 730a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 73179a947c2STobias Grosser /// the parameter values passed for each kernel argument. 73279a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 73379a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 73479a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 73579a947c2STobias Grosser Value *Parameters); 7361fb9b64dSTobias Grosser }; 7371fb9b64dSTobias Grosser 73879f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 7391abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 7401abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 74179f13b9aSSingapuram Sanjay Srivallabh } 74279f13b9aSSingapuram Sanjay Srivallabh 743fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 744750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 745750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 746750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 747750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 748750160e2STobias Grosser 749fa7b0802STobias Grosser GPUContext = createCallInitContext(); 750abed4969SSiddharth Bhat 751*c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 752fa7b0802STobias Grosser allocateDeviceArrays(); 753b99c1171STobias Grosser else 754b99c1171STobias Grosser prepareManagedDeviceArrays(); 755fa7b0802STobias Grosser } 756fa7b0802STobias Grosser 757fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 758*c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 7597287aeddSTobias Grosser freeDeviceArrays(); 760abed4969SSiddharth Bhat 761fa7b0802STobias Grosser createCallFreeContext(GPUContext); 762fa7b0802STobias Grosser IslNodeBuilder::finalize(); 763fa7b0802STobias Grosser } 764fa7b0802STobias Grosser 765fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 766*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 767*c4a4af47SSiddharth Bhat "Managed memory will directly send host pointers " 768abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 7698ea1fc19STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release()); 770fa7b0802STobias Grosser 771fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 772fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 77313c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7747287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7757287aeddSTobias Grosser DevArrayName.append(Array->name); 776fa7b0802STobias Grosser 77713c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 778aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 779aaabbbf8STobias Grosser if (Offset) 780aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 781aaabbbf8STobias Grosser ArraySize, 782aaabbbf8STobias Grosser Builder.CreateMul(Offset, 783aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 78434eeabbcSSiddharth Bhat const SCEV *SizeSCEV = SE.getSCEV(ArraySize); 78534eeabbcSSiddharth Bhat // It makes no sense to have an array of size 0. The CUDA API will 78634eeabbcSSiddharth Bhat // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We 78734eeabbcSSiddharth Bhat // choose to be defensive and catch this at the compile phase. It is 78834eeabbcSSiddharth Bhat // most likely that we are doing something wrong with size computation. 78934eeabbcSSiddharth Bhat if (SizeSCEV->isZero()) { 79034eeabbcSSiddharth Bhat errs() << getUniqueScopName(&S) 79134eeabbcSSiddharth Bhat << " has computed array size 0: " << *ArraySize 79234eeabbcSSiddharth Bhat << " | for array: " << *(ScopArray->getBasePtr()) 79334eeabbcSSiddharth Bhat << ". This is illegal, exiting.\n"; 79434eeabbcSSiddharth Bhat report_fatal_error("array size was computed to be 0"); 79534eeabbcSSiddharth Bhat } 79634eeabbcSSiddharth Bhat 7977287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7987287aeddSTobias Grosser DevArray->setName(DevArrayName); 79913c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 800fa7b0802STobias Grosser } 801fa7b0802STobias Grosser 802fa7b0802STobias Grosser isl_ast_build_free(Build); 803fa7b0802STobias Grosser } 804fa7b0802STobias Grosser 805b99c1171STobias Grosser void GPUNodeBuilder::prepareManagedDeviceArrays() { 806*c4a4af47SSiddharth Bhat assert(PollyManagedMemory && 807b99c1171STobias Grosser "Device array most only be prepared in managed-memory mode"); 808b99c1171STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 809b99c1171STobias Grosser gpu_array_info *Array = &Prog->array[i]; 810b99c1171STobias Grosser ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user; 811b99c1171STobias Grosser Value *HostPtr; 812b99c1171STobias Grosser 813b99c1171STobias Grosser if (gpu_array_is_scalar(Array)) 814b99c1171STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 815b99c1171STobias Grosser else 816b99c1171STobias Grosser HostPtr = ScopArray->getBasePtr(); 817b99c1171STobias Grosser HostPtr = getLatestValue(HostPtr); 818b99c1171STobias Grosser 819b99c1171STobias Grosser Value *Offset = getArrayOffset(Array); 820b99c1171STobias Grosser if (Offset) { 821b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast( 822b99c1171STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 823b99c1171STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 824b99c1171STobias Grosser } 825b99c1171STobias Grosser 826b99c1171STobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 827b99c1171STobias Grosser DeviceAllocations[ScopArray] = HostPtr; 828b99c1171STobias Grosser } 829b99c1171STobias Grosser } 830b99c1171STobias Grosser 831c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 832c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 833c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 834c1c6a2a6STobias Grosser 835c1c6a2a6STobias Grosser for (auto &F : *M) { 836c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 837c1c6a2a6STobias Grosser continue; 838c1c6a2a6STobias Grosser 839c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 840c1c6a2a6STobias Grosser 841c1c6a2a6STobias Grosser Metadata *Elements[] = { 842c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 843c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 844c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 845c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 846c1c6a2a6STobias Grosser }; 847c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 848c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 849c1c6a2a6STobias Grosser } 850c1c6a2a6STobias Grosser } 851c1c6a2a6STobias Grosser 8527287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 853*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory does not use device arrays"); 85413c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 85513c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 8567287aeddSTobias Grosser } 8577287aeddSTobias Grosser 85857793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 85957793596STobias Grosser const char *Name = "polly_getKernel"; 86057793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 86157793596STobias Grosser Function *F = M->getFunction(Name); 86257793596STobias Grosser 86357793596STobias Grosser // If F is not available, declare it. 86457793596STobias Grosser if (!F) { 86557793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 86657793596STobias Grosser std::vector<Type *> Args; 86757793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 86857793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 86957793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 87057793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 87157793596STobias Grosser } 87257793596STobias Grosser 87357793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 87457793596STobias Grosser } 87557793596STobias Grosser 87679a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 87779a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 87879a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 87979a947c2STobias Grosser Function *F = M->getFunction(Name); 88079a947c2STobias Grosser 88179a947c2STobias Grosser // If F is not available, declare it. 88279a947c2STobias Grosser if (!F) { 88379a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 88479a947c2STobias Grosser std::vector<Type *> Args; 88579a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 88679a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 88779a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 88879a947c2STobias Grosser } 88979a947c2STobias Grosser 89079a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 89179a947c2STobias Grosser } 89279a947c2STobias Grosser 89379a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 89479a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 89579a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 89679a947c2STobias Grosser Value *Parameters) { 89779a947c2STobias Grosser const char *Name = "polly_launchKernel"; 89879a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 89979a947c2STobias Grosser Function *F = M->getFunction(Name); 90079a947c2STobias Grosser 90179a947c2STobias Grosser // If F is not available, declare it. 90279a947c2STobias Grosser if (!F) { 90379a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 90479a947c2STobias Grosser std::vector<Type *> Args; 90579a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 90679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 90779a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 90879a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 90979a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91079a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 91179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91279a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 91379a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 91479a947c2STobias Grosser } 91579a947c2STobias Grosser 916ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 91779a947c2STobias Grosser BlockDimZ, Parameters}); 91879a947c2STobias Grosser } 91979a947c2STobias Grosser 92057793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 92157793596STobias Grosser const char *Name = "polly_freeKernel"; 92257793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 92357793596STobias Grosser Function *F = M->getFunction(Name); 92457793596STobias Grosser 92557793596STobias Grosser // If F is not available, declare it. 92657793596STobias Grosser if (!F) { 92757793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 92857793596STobias Grosser std::vector<Type *> Args; 92957793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93057793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 93157793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 93257793596STobias Grosser } 93357793596STobias Grosser 93457793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 93557793596STobias Grosser } 93657793596STobias Grosser 9377287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 938*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 939*c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 940abed4969SSiddharth Bhat "for device"); 9417287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 9427287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9437287aeddSTobias Grosser Function *F = M->getFunction(Name); 9447287aeddSTobias Grosser 9457287aeddSTobias Grosser // If F is not available, declare it. 9467287aeddSTobias Grosser if (!F) { 9477287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 9487287aeddSTobias Grosser std::vector<Type *> Args; 9497287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 9507287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 9517287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 9527287aeddSTobias Grosser } 9537287aeddSTobias Grosser 9547287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 9557287aeddSTobias Grosser } 9567287aeddSTobias Grosser 957fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 958*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 959*c4a4af47SSiddharth Bhat "Managed memory does not allocate or free memory " 960abed4969SSiddharth Bhat "for device"); 961fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 962fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 963fa7b0802STobias Grosser Function *F = M->getFunction(Name); 964fa7b0802STobias Grosser 965fa7b0802STobias Grosser // If F is not available, declare it. 966fa7b0802STobias Grosser if (!F) { 967fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 968fa7b0802STobias Grosser std::vector<Type *> Args; 969fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 970fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 971fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 972fa7b0802STobias Grosser } 973fa7b0802STobias Grosser 974fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 975fa7b0802STobias Grosser } 976fa7b0802STobias Grosser 97713c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 97813c78e4dSTobias Grosser Value *DeviceData, 97913c78e4dSTobias Grosser Value *Size) { 980*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 981*c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 982abed4969SSiddharth Bhat "device and host"); 98313c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 98413c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 98513c78e4dSTobias Grosser Function *F = M->getFunction(Name); 98613c78e4dSTobias Grosser 98713c78e4dSTobias Grosser // If F is not available, declare it. 98813c78e4dSTobias Grosser if (!F) { 98913c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 99013c78e4dSTobias Grosser std::vector<Type *> Args; 99113c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99213c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 99313c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 99413c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 99513c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 99613c78e4dSTobias Grosser } 99713c78e4dSTobias Grosser 99813c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 99913c78e4dSTobias Grosser } 100013c78e4dSTobias Grosser 100113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 100213c78e4dSTobias Grosser Value *HostData, 100313c78e4dSTobias Grosser Value *Size) { 1004*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && 1005*c4a4af47SSiddharth Bhat "Managed memory does not transfer memory between " 1006abed4969SSiddharth Bhat "device and host"); 100713c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 100813c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 100913c78e4dSTobias Grosser Function *F = M->getFunction(Name); 101013c78e4dSTobias Grosser 101113c78e4dSTobias Grosser // If F is not available, declare it. 101213c78e4dSTobias Grosser if (!F) { 101313c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 101413c78e4dSTobias Grosser std::vector<Type *> Args; 101513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 101613c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 101713c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 101813c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 101913c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 102013c78e4dSTobias Grosser } 102113c78e4dSTobias Grosser 102213c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 102313c78e4dSTobias Grosser } 102413c78e4dSTobias Grosser 1025abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 1026*c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "explicit synchronization is only necessary for " 1027abed4969SSiddharth Bhat "managed memory"); 1028abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 1029abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1030abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 1031abed4969SSiddharth Bhat 1032abed4969SSiddharth Bhat // If F is not available, declare it. 1033abed4969SSiddharth Bhat if (!F) { 1034abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1035abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 1036abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 1037abed4969SSiddharth Bhat } 1038abed4969SSiddharth Bhat 1039abed4969SSiddharth Bhat Builder.CreateCall(F); 1040abed4969SSiddharth Bhat } 1041abed4969SSiddharth Bhat 1042fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 104317f01968SSiddharth Bhat const char *Name; 104417f01968SSiddharth Bhat 104517f01968SSiddharth Bhat switch (Runtime) { 104617f01968SSiddharth Bhat case GPURuntime::CUDA: 104717f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 104817f01968SSiddharth Bhat break; 104917f01968SSiddharth Bhat case GPURuntime::OpenCL: 105017f01968SSiddharth Bhat Name = "polly_initContextCL"; 105117f01968SSiddharth Bhat break; 105217f01968SSiddharth Bhat } 105317f01968SSiddharth Bhat 1054fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1055fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1056fa7b0802STobias Grosser 1057fa7b0802STobias Grosser // If F is not available, declare it. 1058fa7b0802STobias Grosser if (!F) { 1059fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1060fa7b0802STobias Grosser std::vector<Type *> Args; 1061fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1062fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1063fa7b0802STobias Grosser } 1064fa7b0802STobias Grosser 1065fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 1066fa7b0802STobias Grosser } 1067fa7b0802STobias Grosser 1068fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 1069fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 1070fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1071fa7b0802STobias Grosser Function *F = M->getFunction(Name); 1072fa7b0802STobias Grosser 1073fa7b0802STobias Grosser // If F is not available, declare it. 1074fa7b0802STobias Grosser if (!F) { 1075fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1076fa7b0802STobias Grosser std::vector<Type *> Args; 1077fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 1078fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1079fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1080fa7b0802STobias Grosser } 1081fa7b0802STobias Grosser 1082fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 1083fa7b0802STobias Grosser } 1084fa7b0802STobias Grosser 10855260c041STobias Grosser /// Check if one string is a prefix of another. 10865260c041STobias Grosser /// 10875260c041STobias Grosser /// @param String The string in which to look for the prefix. 10885260c041STobias Grosser /// @param Prefix The prefix to look for. 10895260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 10905260c041STobias Grosser return String.find(Prefix) == 0; 10915260c041STobias Grosser } 10925260c041STobias Grosser 109313c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1094b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 109513c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 109613c78e4dSTobias Grosser 109713c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 1098f7face4bSSiddharth Bhat isl::multi_pw_aff ArrayBound = 1099f7face4bSSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Array->bound)); 1100f7face4bSSiddharth Bhat 1101f7face4bSSiddharth Bhat isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0); 1102f7face4bSSiddharth Bhat isl::ast_expr Res = Build.expr_from(OffsetDimZero); 110313c78e4dSTobias Grosser 110413c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 1105f7face4bSSiddharth Bhat isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i); 1106f7face4bSSiddharth Bhat isl::ast_expr Expr = Build.expr_from(Bound_I); 1107f7face4bSSiddharth Bhat Res = Res.mul(Expr); 110813c78e4dSTobias Grosser } 110913c78e4dSTobias Grosser 1110f7face4bSSiddharth Bhat Value *NumElements = ExprBuilder.create(Res.release()); 1111b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1112b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 111313c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 111413c78e4dSTobias Grosser } 111513c78e4dSTobias Grosser return ArraySize; 111613c78e4dSTobias Grosser } 111713c78e4dSTobias Grosser 1118aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1119aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1120aaabbbf8STobias Grosser return nullptr; 1121aaabbbf8STobias Grosser 1122b65ccc43STobias Grosser isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1123aaabbbf8STobias Grosser 1124ccbf4b50SSiddharth Bhat isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin(); 1125aaabbbf8STobias Grosser 1126ccbf4b50SSiddharth Bhat isl::set ZeroSet = isl::set::universe(Min.get_space()); 1127aaabbbf8STobias Grosser 1128ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) 1129ccbf4b50SSiddharth Bhat ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1130aaabbbf8STobias Grosser 1131ccbf4b50SSiddharth Bhat if (Min.is_subset(ZeroSet)) { 1132aaabbbf8STobias Grosser return nullptr; 1133aaabbbf8STobias Grosser } 1134aaabbbf8STobias Grosser 1135ccbf4b50SSiddharth Bhat isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0)); 1136aaabbbf8STobias Grosser 1137ccbf4b50SSiddharth Bhat for (long i = 0; i < Min.dim(isl::dim::set); i++) { 1138aaabbbf8STobias Grosser if (i > 0) { 1139ccbf4b50SSiddharth Bhat isl::pw_aff Bound_I = 1140ccbf4b50SSiddharth Bhat isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1141ccbf4b50SSiddharth Bhat isl::ast_expr BExpr = Build.expr_from(Bound_I); 1142ccbf4b50SSiddharth Bhat Result = Result.mul(BExpr); 1143aaabbbf8STobias Grosser } 1144ccbf4b50SSiddharth Bhat isl::pw_aff DimMin = Min.dim_min(i); 1145ccbf4b50SSiddharth Bhat isl::ast_expr MExpr = Build.expr_from(DimMin); 1146ccbf4b50SSiddharth Bhat Result = Result.add(MExpr); 1147aaabbbf8STobias Grosser } 1148aaabbbf8STobias Grosser 1149ccbf4b50SSiddharth Bhat return ExprBuilder.create(Result.release()); 1150aaabbbf8STobias Grosser } 1151aaabbbf8STobias Grosser 1152b99c1171STobias Grosser Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1153abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1154*c4a4af47SSiddharth Bhat assert(PollyManagedMemory && "Only used when you wish to get a host " 1155abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1156abed4969SSiddharth Bhat "with managed memory"); 1157abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1158b99c1171STobias Grosser it = DeviceAllocations.find(ArrayInfo); 1159b99c1171STobias Grosser assert(it != DeviceAllocations.end() && 1160b99c1171STobias Grosser "Device array expected to be available"); 1161abed4969SSiddharth Bhat return it->second; 1162abed4969SSiddharth Bhat } 1163abed4969SSiddharth Bhat 116413c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 116513c78e4dSTobias Grosser enum DataDirection Direction) { 1166*c4a4af47SSiddharth Bhat assert(!PollyManagedMemory && "Managed memory needs no data transfers"); 116713c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 116813c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 116913c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 117013c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 117113c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 117213c78e4dSTobias Grosser 117313c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1174aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 117513c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 117613c78e4dSTobias Grosser 1177b06ff457STobias Grosser Value *HostPtr; 1178b06ff457STobias Grosser 1179b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1180b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1181b06ff457STobias Grosser else 1182b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 1183edf9581eSSiddharth Bhat HostPtr = getLatestValue(HostPtr); 118413c78e4dSTobias Grosser 1185aaabbbf8STobias Grosser if (Offset) { 1186aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1187aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1188aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1189aaabbbf8STobias Grosser } 1190aaabbbf8STobias Grosser 119113c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 119213c78e4dSTobias Grosser 1193aaabbbf8STobias Grosser if (Offset) { 1194aaabbbf8STobias Grosser Size = Builder.CreateSub( 1195ff40087aSTobias Grosser Size, Builder.CreateMul( 1196ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1197aaabbbf8STobias Grosser } 1198aaabbbf8STobias Grosser 119913c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 120013c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 120113c78e4dSTobias Grosser else 120213c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 120313c78e4dSTobias Grosser 120413c78e4dSTobias Grosser isl_id_free(Id); 120513c78e4dSTobias Grosser isl_ast_expr_free(Arg); 120613c78e4dSTobias Grosser isl_ast_expr_free(Expr); 120713c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 120813c78e4dSTobias Grosser } 120913c78e4dSTobias Grosser 12101fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 121132837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 121232837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 121332837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 121432837fe3STobias Grosser isl_id_free(Id); 121532837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 121632837fe3STobias Grosser 121732837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 121832837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 121932837fe3STobias Grosser createKernel(UserStmt); 122032837fe3STobias Grosser isl_ast_expr_free(Expr); 122132837fe3STobias Grosser return; 122232837fe3STobias Grosser } 12239e3db2b7SSiddharth Bhat if (!strcmp(Str, "init_device")) { 12249e3db2b7SSiddharth Bhat initializeAfterRTH(); 12259e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12269e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12279e3db2b7SSiddharth Bhat return; 12289e3db2b7SSiddharth Bhat } 12299e3db2b7SSiddharth Bhat if (!strcmp(Str, "clear_device")) { 12309e3db2b7SSiddharth Bhat finalize(); 12319e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 12329e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 12339e3db2b7SSiddharth Bhat return; 12349e3db2b7SSiddharth Bhat } 123513c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1236*c4a4af47SSiddharth Bhat if (!PollyManagedMemory) 123713c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1238abed4969SSiddharth Bhat else 1239abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1240abed4969SSiddharth Bhat 124132837fe3STobias Grosser isl_ast_expr_free(Expr); 124213c78e4dSTobias Grosser return; 124313c78e4dSTobias Grosser } 124413c78e4dSTobias Grosser 124513c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1246*c4a4af47SSiddharth Bhat if (!PollyManagedMemory) { 124713c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1248abed4969SSiddharth Bhat } else { 1249abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1250abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1251abed4969SSiddharth Bhat } 125213c78e4dSTobias Grosser isl_ast_expr_free(Expr); 125338fc0aedSTobias Grosser return; 125438fc0aedSTobias Grosser } 125538fc0aedSTobias Grosser 12565260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 12575260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 12585260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 12595260c041STobias Grosser isl_id_free(Anno); 12605260c041STobias Grosser 12615260c041STobias Grosser switch (KernelStmt->type) { 12625260c041STobias Grosser case ppcg_kernel_domain: 1263edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 12645260c041STobias Grosser isl_ast_node_free(UserStmt); 12655260c041STobias Grosser return; 12665260c041STobias Grosser case ppcg_kernel_copy: 1267b513b491STobias Grosser createKernelCopy(KernelStmt); 12685260c041STobias Grosser isl_ast_expr_free(Expr); 12695260c041STobias Grosser isl_ast_node_free(UserStmt); 12705260c041STobias Grosser return; 12715260c041STobias Grosser case ppcg_kernel_sync: 12725260c041STobias Grosser createKernelSync(); 12735260c041STobias Grosser isl_ast_expr_free(Expr); 12745260c041STobias Grosser isl_ast_node_free(UserStmt); 12755260c041STobias Grosser return; 12765260c041STobias Grosser } 12775260c041STobias Grosser 12785260c041STobias Grosser isl_ast_expr_free(Expr); 12795260c041STobias Grosser isl_ast_node_free(UserStmt); 12805260c041STobias Grosser return; 12815260c041STobias Grosser } 1282b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1283b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1284b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1285b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1286b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1287b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1288b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1289b513b491STobias Grosser 1290b513b491STobias Grosser if (KernelStmt->u.c.read) { 1291b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1292b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1293b513b491STobias Grosser } else { 1294b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1295b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1296b513b491STobias Grosser } 1297b513b491STobias Grosser } 12985260c041STobias Grosser 1299edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1300edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1301edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1302edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1303edb885cbSTobias Grosser 1304edb885cbSTobias Grosser LoopToScevMapT LTS; 1305edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1306edb885cbSTobias Grosser 1307edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1308edb885cbSTobias Grosser 1309edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1310edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1311edb885cbSTobias Grosser else 1312a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1313edb885cbSTobias Grosser } 1314edb885cbSTobias Grosser 13155260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 13165260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13172f3073b5SPhilipp Schaad const char *SpirName = "__gen_ocl_barrier_global"; 131817f01968SSiddharth Bhat 131917f01968SSiddharth Bhat Function *Sync; 132017f01968SSiddharth Bhat 132117f01968SSiddharth Bhat switch (Arch) { 13222f3073b5SPhilipp Schaad case GPUArch::SPIR64: 13232f3073b5SPhilipp Schaad case GPUArch::SPIR32: 13242f3073b5SPhilipp Schaad Sync = M->getFunction(SpirName); 13252f3073b5SPhilipp Schaad 13262f3073b5SPhilipp Schaad // If Sync is not available, declare it. 13272f3073b5SPhilipp Schaad if (!Sync) { 13282f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 13292f3073b5SPhilipp Schaad std::vector<Type *> Args; 13302f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 13312f3073b5SPhilipp Schaad Sync = Function::Create(Ty, Linkage, SpirName, M); 13322f3073b5SPhilipp Schaad Sync->setCallingConv(CallingConv::SPIR_FUNC); 13332f3073b5SPhilipp Schaad } 13342f3073b5SPhilipp Schaad break; 133517f01968SSiddharth Bhat case GPUArch::NVPTX64: 133617f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 133717f01968SSiddharth Bhat break; 133817f01968SSiddharth Bhat } 133917f01968SSiddharth Bhat 13405260c041STobias Grosser Builder.CreateCall(Sync, {}); 13415260c041STobias Grosser } 13425260c041STobias Grosser 1343edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1344edb885cbSTobias Grosser /// 1345edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1346edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1347edb885cbSTobias Grosser /// 1348edb885cbSTobias Grosser /// @param Node The node to collect references for. 1349edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1350edb885cbSTobias Grosser /// 1351edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1352edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1353edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1354edb885cbSTobias Grosser return isl_bool_true; 1355edb885cbSTobias Grosser 1356edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1357edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1358edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1359edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1360edb885cbSTobias Grosser isl_id_free(Id); 1361edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1362edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1363edb885cbSTobias Grosser 1364edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1365edb885cbSTobias Grosser return isl_bool_true; 1366edb885cbSTobias Grosser 1367edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1368edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1369edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1370edb885cbSTobias Grosser isl_id_free(Id); 1371edb885cbSTobias Grosser 137200bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1373edb885cbSTobias Grosser 1374edb885cbSTobias Grosser return isl_bool_true; 1375edb885cbSTobias Grosser } 1376edb885cbSTobias Grosser 13778fc6cdfbSTobias Grosser /// A list of functions that are available in NVIDIA's libdevice. 13788fc6cdfbSTobias Grosser const std::set<std::string> CUDALibDeviceFunctions = { 13798fc6cdfbSTobias Grosser "exp", "expf", "expl", "cos", "cosf", 13808fc6cdfbSTobias Grosser "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"}; 13818fc6cdfbSTobias Grosser 13828fc6cdfbSTobias Grosser /// Return the corresponding CUDA libdevice function name for @p F. 13838fc6cdfbSTobias Grosser /// 13848fc6cdfbSTobias Grosser /// Return "" if we are not compiling for CUDA. 13858fc6cdfbSTobias Grosser std::string getCUDALibDeviceFuntion(Function *F) { 13868fc6cdfbSTobias Grosser if (CUDALibDeviceFunctions.count(F->getName())) 13878fc6cdfbSTobias Grosser return std::string("__nv_") + std::string(F->getName()); 13888fc6cdfbSTobias Grosser 13898fc6cdfbSTobias Grosser return ""; 13908fc6cdfbSTobias Grosser } 13918fc6cdfbSTobias Grosser 1392f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 13938fc6cdfbSTobias Grosser static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1394f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1395f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 139654491db6STobias Grosser // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 139754491db6STobias Grosser // "llvm.copysign". 139854491db6STobias Grosser const StringRef Name = F->getName(); 13998fc6cdfbSTobias Grosser 14008fc6cdfbSTobias Grosser if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0) 14018fc6cdfbSTobias Grosser return true; 14028fc6cdfbSTobias Grosser 140354491db6STobias Grosser return F->isIntrinsic() && 140454491db6STobias Grosser (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 140554491db6STobias Grosser Name.startswith("llvm.copysign")); 1406f291c8d5SSiddharth Bhat } 1407f291c8d5SSiddharth Bhat 1408f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1409f291c8d5SSiddharth Bhat /// 1410f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1411f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1412f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1413f291c8d5SSiddharth Bhat /// `Function`s. 1414f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1415f291c8d5SSiddharth Bhat 1416f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1417f291c8d5SSiddharth Bhat static SetVector<Function *> 14188fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 14198fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 1420f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1421f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1422f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1423f291c8d5SSiddharth Bhat if (F) { 14248fc6cdfbSTobias Grosser assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 14258fc6cdfbSTobias Grosser "Code should have bailed out by " 1426f291c8d5SSiddharth Bhat "this point if an invalid function " 1427f291c8d5SSiddharth Bhat "were present in a kernel."); 1428f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1429f291c8d5SSiddharth Bhat } 1430f291c8d5SSiddharth Bhat } 1431f291c8d5SSiddharth Bhat return SubtreeFunctions; 1432f291c8d5SSiddharth Bhat } 1433f291c8d5SSiddharth Bhat 1434e53c924bSSiddharth Bhat std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>> 1435f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1436edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1437edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1438edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1439edb885cbSTobias Grosser SubtreeReferences References = { 1440edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1441edb885cbSTobias Grosser 1442edb885cbSTobias Grosser for (const auto &I : IDToValue) 1443edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1444edb885cbSTobias Grosser 1445e53c924bSSiddharth Bhat // NOTE: this is populated in IslNodeBuilder::addParameters 1446e53c924bSSiddharth Bhat // See [Code generation of induction variables of loops outside Scops]. 1447e53c924bSSiddharth Bhat for (const auto &I : OutsideLoopIterations) 1448e53c924bSSiddharth Bhat SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1449e53c924bSSiddharth Bhat 1450edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1451edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1452edb885cbSTobias Grosser 1453e53c924bSSiddharth Bhat for (const SCEV *Expr : SCEVs) { 1454edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1455e53c924bSSiddharth Bhat findLoops(Expr, Loops); 1456e53c924bSSiddharth Bhat } 1457e53c924bSSiddharth Bhat 1458e53c924bSSiddharth Bhat Loops.remove_if([this](const Loop *L) { 1459e53c924bSSiddharth Bhat return S.contains(L) || L->contains(S.getEntry()); 1460e53c924bSSiddharth Bhat }); 1461edb885cbSTobias Grosser 1462edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1463d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1464edb885cbSTobias Grosser 1465b65ccc43STobias Grosser isl_space *Space = S.getParamSpace().release(); 1466edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1467edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1468edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1469edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1470edb885cbSTobias Grosser SubtreeValues.remove(Val); 1471edb885cbSTobias Grosser isl_id_free(Id); 1472edb885cbSTobias Grosser } 1473edb885cbSTobias Grosser isl_space_free(Space); 1474edb885cbSTobias Grosser 1475edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1476edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1477edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1478edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1479edb885cbSTobias Grosser SubtreeValues.remove(Val); 1480edb885cbSTobias Grosser isl_id_free(Id); 1481edb885cbSTobias Grosser } 1482edb885cbSTobias Grosser 1483f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1484f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1485f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1486f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1487f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1488f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1489f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1490f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1491f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 14928fc6cdfbSTobias Grosser 14938fc6cdfbSTobias Grosser bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 14948fc6cdfbSTobias Grosser 1495f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 14968fc6cdfbSTobias Grosser getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1497f291c8d5SSiddharth Bhat 1498a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1499a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1500a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1501a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1502a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1503a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1504a1b2086aSSiddharth Bhat else 1505a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1506a1b2086aSSiddharth Bhat } 1507e53c924bSSiddharth Bhat return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops); 1508edb885cbSTobias Grosser } 1509edb885cbSTobias Grosser 151074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 151174dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 151274dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 151374dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 151474dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 151574dc3cb4STobias Grosser 151674dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 151774dc3cb4STobias Grosser DT.eraseNode(BB); 151874dc3cb4STobias Grosser } 151974dc3cb4STobias Grosser 152074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 152174dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 152274dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 152374dc3cb4STobias Grosser if (L) 152474dc3cb4STobias Grosser SE.forgetLoop(L); 152574dc3cb4STobias Grosser } 152674dc3cb4STobias Grosser } 152774dc3cb4STobias Grosser 152874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(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 LI.removeBlock(&BB); 153474dc3cb4STobias Grosser } 153574dc3cb4STobias Grosser } 153674dc3cb4STobias Grosser 153779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 153879a947c2STobias Grosser std::vector<Value *> Sizes; 15398ea1fc19STobias Grosser isl::ast_build Context = isl::ast_build::from_context(S.getContext()); 154079a947c2STobias Grosser 15414d5820d1SSiddharth Bhat isl::multi_pw_aff GridSizePwAffs = 15424d5820d1SSiddharth Bhat isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size)); 154379a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 15444d5820d1SSiddharth Bhat isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i); 15454d5820d1SSiddharth Bhat isl::ast_expr GridSize = Context.expr_from(Size); 15464d5820d1SSiddharth Bhat Value *Res = ExprBuilder.create(GridSize.release()); 154779a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 154879a947c2STobias Grosser Sizes.push_back(Res); 154979a947c2STobias Grosser } 155079a947c2STobias Grosser 155179a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 155279a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 155379a947c2STobias Grosser 155479a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 155579a947c2STobias Grosser } 155679a947c2STobias Grosser 155779a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 155879a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 155979a947c2STobias Grosser std::vector<Value *> Sizes; 156079a947c2STobias Grosser 156179a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 156279a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 156379a947c2STobias Grosser Sizes.push_back(Res); 156479a947c2STobias Grosser } 156579a947c2STobias Grosser 156679a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 156779a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 156879a947c2STobias Grosser 156979a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 157079a947c2STobias Grosser } 157179a947c2STobias Grosser 1572a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1573a90be207SSiddharth Bhat Instruction *Param, int Index) { 1574a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1575a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1576a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1577a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1578a90be207SSiddharth Bhat } 1579a90be207SSiddharth Bhat 158057693272STobias Grosser Value * 158157693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 158257693272STobias Grosser SetVector<Value *> SubtreeValues) { 1583a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1584a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1585a90be207SSiddharth Bhat 1586a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 158779a947c2STobias Grosser 158879a947c2STobias Grosser BasicBlock *EntryBlock = 158979a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 159067726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 159179a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 159267726b32STobias Grosser Instruction *Parameters = new AllocaInst( 159367726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 159479a947c2STobias Grosser 159579a947c2STobias Grosser int Index = 0; 159679a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 159779a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 159879a947c2STobias Grosser continue; 159979a947c2STobias Grosser 160079a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1601206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 160279a947c2STobias Grosser 1603a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1604a90be207SSiddharth Bhat 1605abed4969SSiddharth Bhat Value *DevArray = nullptr; 1606*c4a4af47SSiddharth Bhat if (PollyManagedMemory) { 1607b99c1171STobias Grosser DevArray = getManagedDeviceArray(&Prog->array[i], 1608b99c1171STobias Grosser const_cast<ScopArrayInfo *>(SAI)); 1609abed4969SSiddharth Bhat } else { 1610abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 161179a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1612abed4969SSiddharth Bhat } 1613abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1614abed4969SSiddharth Bhat "initialized"); 1615aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1616aaabbbf8STobias Grosser 1617aaabbbf8STobias Grosser if (Offset) { 1618aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1619aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1620aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1621aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1622aaabbbf8STobias Grosser } 1623fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1624fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1625aaabbbf8STobias Grosser 1626fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1627abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1628*c4a4af47SSiddharth Bhat if (PollyManagedMemory) 1629abed4969SSiddharth Bhat ValPtr = DevArray; 1630abed4969SSiddharth Bhat else 1631abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1632abed4969SSiddharth Bhat 1633abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1634abed4969SSiddharth Bhat " to be stored into Parameters"); 1635fe74a7a1STobias Grosser Value *ValPtrCast = 1636fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1637fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1638fe74a7a1STobias Grosser } else { 163967726b32STobias Grosser Instruction *Param = 164067726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 164167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 164279a947c2STobias Grosser EntryBlock->getTerminator()); 164379a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 164479a947c2STobias Grosser Value *ParamTyped = 164579a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 164679a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1647fe74a7a1STobias Grosser } 164879a947c2STobias Grosser Index++; 164979a947c2STobias Grosser } 165079a947c2STobias Grosser 1651a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1652a490147cSTobias Grosser 1653a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1654a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1655a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1656a490147cSTobias Grosser isl_id_free(Id); 1657a90be207SSiddharth Bhat 1658a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1659a90be207SSiddharth Bhat 166067726b32STobias Grosser Instruction *Param = 166167726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 166267726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1663a490147cSTobias Grosser EntryBlock->getTerminator()); 1664a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1665a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1666a490147cSTobias Grosser Index++; 1667a490147cSTobias Grosser } 1668a490147cSTobias Grosser 1669d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1670d8b94bcaSTobias Grosser 1671d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1672d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1673d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1674a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1675a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1676d8b94bcaSTobias Grosser isl_id_free(Id); 1677a90be207SSiddharth Bhat 1678a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1679a90be207SSiddharth Bhat 168067726b32STobias Grosser Instruction *Param = 168167726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 168267726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1683d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1684d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1685a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1686d8b94bcaSTobias Grosser Index++; 1687d8b94bcaSTobias Grosser } 1688d8b94bcaSTobias Grosser 168957693272STobias Grosser for (auto Val : SubtreeValues) { 1690a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1691a90be207SSiddharth Bhat 169267726b32STobias Grosser Instruction *Param = 169367726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 169467726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 169557693272STobias Grosser EntryBlock->getTerminator()); 169657693272STobias Grosser Builder.CreateStore(Val, Param); 1697a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1698a90be207SSiddharth Bhat Index++; 1699a90be207SSiddharth Bhat } 1700a90be207SSiddharth Bhat 1701a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1702a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1703a90be207SSiddharth Bhat Instruction *Param = 1704a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1705a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1706a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1707a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1708a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 170957693272STobias Grosser Index++; 171057693272STobias Grosser } 171157693272STobias Grosser 171279a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 171379a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 171479a947c2STobias Grosser Launch + "_params_i8ptr", Location); 171579a947c2STobias Grosser } 171679a947c2STobias Grosser 1717f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1718f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1719f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1720f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1721f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1722f291c8d5SSiddharth Bhat if (!Clone) 1723f291c8d5SSiddharth Bhat Clone = 1724f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1725f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1726f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1727f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1728f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1729f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1730f291c8d5SSiddharth Bhat } 1731f291c8d5SSiddharth Bhat } 173232837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 173332837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 173432837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 173532837fe3STobias Grosser isl_id_free(Id); 173632837fe3STobias Grosser isl_ast_node_free(KernelStmt); 173732837fe3STobias Grosser 1738bc653f20STobias Grosser if (Kernel->n_grid > 1) 1739bc653f20STobias Grosser DeepestParallel = 1740bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1741bc653f20STobias Grosser else 1742bc653f20STobias Grosser DeepestSequential = 1743bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1744bc653f20STobias Grosser 1745c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1746c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1747c1c6a2a6STobias Grosser 1748f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1749f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1750e53c924bSSiddharth Bhat SetVector<const Loop *> Loops; 1751e53c924bSSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions, Loops) = 1752e53c924bSSiddharth Bhat getReferencesInKernel(Kernel); 1753edb885cbSTobias Grosser 175432837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 175532837fe3STobias Grosser 175632837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1757472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1758edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1759587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1760b06ff457STobias Grosser ScalarMap.clear(); 176132837fe3STobias Grosser 1762edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1763edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1764edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1765edb885cbSTobias Grosser for (const Loop *L : Loops) { 1766edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1767edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1768edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1769edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1770edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1771edb885cbSTobias Grosser SubtreeValues.insert(V); 1772edb885cbSTobias Grosser } 1773edb885cbSTobias Grosser 1774f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1775f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 177632837fe3STobias Grosser 177759ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 177859ab0705STobias Grosser 177951dfc275STobias Grosser finalizeKernelArguments(Kernel); 178074dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 17812f3073b5SPhilipp Schaad if (Arch == GPUArch::NVPTX64) 1782c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 178374dc3cb4STobias Grosser clearDominators(F); 178474dc3cb4STobias Grosser clearScalarEvolution(F); 178574dc3cb4STobias Grosser clearLoops(F); 178674dc3cb4STobias Grosser 1787472f9654STobias Grosser IDToValue = HostIDs; 178832837fe3STobias Grosser 1789b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1790b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1791edb885cbSTobias Grosser EscapeMap.clear(); 1792edb885cbSTobias Grosser IDToSAI.clear(); 179374dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 179474dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 17954d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 179674dc3cb4STobias Grosser LocalArrays.clear(); 1797edb885cbSTobias Grosser 179851dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 179951dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 180057693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 180179a947c2STobias Grosser 180279f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 180357793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 180457793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 180557793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 180679a947c2STobias Grosser 180779a947c2STobias Grosser Value *GridDimX, *GridDimY; 180879a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 180979a947c2STobias Grosser 181079a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 181179a947c2STobias Grosser BlockDimZ, Parameters); 181257793596STobias Grosser createCallFreeKernel(GPUKernel); 1813b513b491STobias Grosser 1814b513b491STobias Grosser for (auto Id : KernelIds) 1815b513b491STobias Grosser isl_id_free(Id); 1816b513b491STobias Grosser 1817b513b491STobias Grosser KernelIds.clear(); 181832837fe3STobias Grosser } 181932837fe3STobias Grosser 182032837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 182132837fe3STobias Grosser /// 182232837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 182332837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1824d277fedaSSiddharth Bhat std::string Ret = ""; 182532837fe3STobias Grosser 1826d277fedaSSiddharth Bhat if (!is64Bit) { 1827d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 182830caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1829d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1830d277fedaSSiddharth Bhat } else { 1831d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 183230caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1833d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1834d277fedaSSiddharth Bhat } 183532837fe3STobias Grosser 183632837fe3STobias Grosser return Ret; 183732837fe3STobias Grosser } 183832837fe3STobias Grosser 18392f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel. 18402f3073b5SPhilipp Schaad /// 18412f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture? 18422f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) { 18432f3073b5SPhilipp Schaad std::string Ret = ""; 18442f3073b5SPhilipp Schaad 18452f3073b5SPhilipp Schaad if (!is64Bit) { 18462f3073b5SPhilipp Schaad Ret += "e-p:32:32:32-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-v24:32:32-v32:32:" 18482f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18492f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18502f3073b5SPhilipp Schaad } else { 18512f3073b5SPhilipp Schaad Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 185230caae6dSTobias Grosser "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 18532f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 18542f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 18552f3073b5SPhilipp Schaad } 18562f3073b5SPhilipp Schaad 18572f3073b5SPhilipp Schaad return Ret; 18582f3073b5SPhilipp Schaad } 18592f3073b5SPhilipp Schaad 1860edb885cbSTobias Grosser Function * 1861edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1862edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 186332837fe3STobias Grosser std::vector<Type *> Args; 186479f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 186532837fe3STobias Grosser 18662f3073b5SPhilipp Schaad std::vector<Metadata *> MemoryType; 18672f3073b5SPhilipp Schaad 186832837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 186932837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 187032837fe3STobias Grosser continue; 187132837fe3STobias Grosser 1872fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1873fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1874206e9e3bSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1875fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 18762f3073b5SPhilipp Schaad MemoryType.push_back( 18772f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1878fe74a7a1STobias Grosser } else { 1879d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1880d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 18812f3073b5SPhilipp Schaad MemoryType.push_back( 18822f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 188332837fe3STobias Grosser } 1884fe74a7a1STobias Grosser } 188532837fe3STobias Grosser 1886f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1887f6044bd0STobias Grosser 18882f3073b5SPhilipp Schaad for (long i = 0; i < NumHostIters; i++) { 1889f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 18902f3073b5SPhilipp Schaad MemoryType.push_back( 18912f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 18922f3073b5SPhilipp Schaad } 1893f6044bd0STobias Grosser 1894c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1895c84a1995STobias Grosser 1896cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1897cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1898cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1899cf66ef26STobias Grosser isl_id_free(Id); 1900cf66ef26STobias Grosser Args.push_back(Val->getType()); 19012f3073b5SPhilipp Schaad MemoryType.push_back( 19022f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1903cf66ef26STobias Grosser } 1904c84a1995STobias Grosser 19052f3073b5SPhilipp Schaad for (auto *V : SubtreeValues) { 1906edb885cbSTobias Grosser Args.push_back(V->getType()); 19072f3073b5SPhilipp Schaad MemoryType.push_back( 19082f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 19092f3073b5SPhilipp Schaad } 1910edb885cbSTobias Grosser 191132837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 191232837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 191332837fe3STobias Grosser GPUModule.get()); 191417f01968SSiddharth Bhat 19152f3073b5SPhilipp Schaad std::vector<Metadata *> EmptyStrings; 19162f3073b5SPhilipp Schaad 19172f3073b5SPhilipp Schaad for (unsigned int i = 0; i < MemoryType.size(); i++) { 19182f3073b5SPhilipp Schaad EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 19192f3073b5SPhilipp Schaad } 19202f3073b5SPhilipp Schaad 19212f3073b5SPhilipp Schaad if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 19222f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_addr_space", 19232f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), MemoryType)); 19242f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_name", 19252f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19262f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_access_qual", 19272f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19282f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type", 19292f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19302f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type_qual", 19312f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19322f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_base_type", 19332f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 19342f3073b5SPhilipp Schaad } 19352f3073b5SPhilipp Schaad 193617f01968SSiddharth Bhat switch (Arch) { 193717f01968SSiddharth Bhat case GPUArch::NVPTX64: 193832837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 193917f01968SSiddharth Bhat break; 19402f3073b5SPhilipp Schaad case GPUArch::SPIR32: 19412f3073b5SPhilipp Schaad case GPUArch::SPIR64: 19422f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_KERNEL); 19432f3073b5SPhilipp Schaad break; 194417f01968SSiddharth Bhat } 194532837fe3STobias Grosser 194632837fe3STobias Grosser auto Arg = FN->arg_begin(); 194732837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 194832837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 194932837fe3STobias Grosser continue; 195032837fe3STobias Grosser 1951edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1952edb885cbSTobias Grosser 1953edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1954206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 1955206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 1956edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1957edb885cbSTobias Grosser Value *Val = &*Arg; 1958edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1959edb885cbSTobias Grosser isl_ast_build *Build = 1960edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1961f5aff704SRoman Gareev Sizes.push_back(nullptr); 1962edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1963edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 19649e3db2b7SSiddharth Bhat Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1965edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1966edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1967edb885cbSTobias Grosser } 1968edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 19694d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 197074dc3cb4STobias Grosser LocalArrays.push_back(Val); 1971edb885cbSTobias Grosser 1972edb885cbSTobias Grosser isl_ast_build_free(Build); 1973b513b491STobias Grosser KernelIds.push_back(Id); 1974edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 197532837fe3STobias Grosser Arg++; 197632837fe3STobias Grosser } 197732837fe3STobias Grosser 1978f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1979f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1980f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1981f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1982f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1983f6044bd0STobias Grosser Arg++; 1984f6044bd0STobias Grosser } 1985f6044bd0STobias Grosser 1986c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1987c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1988c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 198912453403STobias Grosser Value *Val = IDToValue[Id]; 199012453403STobias Grosser ValueMap[Val] = &*Arg; 1991c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1992c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1993c84a1995STobias Grosser Arg++; 1994c84a1995STobias Grosser } 1995c84a1995STobias Grosser 1996edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1997edb885cbSTobias Grosser Arg->setName(V->getName()); 1998edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1999edb885cbSTobias Grosser Arg++; 2000edb885cbSTobias Grosser } 2001edb885cbSTobias Grosser 200232837fe3STobias Grosser return FN; 200332837fe3STobias Grosser } 200432837fe3STobias Grosser 2005472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 200617f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 200717f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 2008472f9654STobias Grosser 200917f01968SSiddharth Bhat switch (Arch) { 20102f3073b5SPhilipp Schaad case GPUArch::SPIR64: 20112f3073b5SPhilipp Schaad case GPUArch::SPIR32: 20122f3073b5SPhilipp Schaad llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 201317f01968SSiddharth Bhat case GPUArch::NVPTX64: 201417f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 201517f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 201617f01968SSiddharth Bhat 201717f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 201817f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 201917f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 202017f01968SSiddharth Bhat break; 202117f01968SSiddharth Bhat } 2022472f9654STobias Grosser 2023472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2024472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 2025472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2026472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2027472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2028472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2029472f9654STobias Grosser IDToValue[Id] = Val; 2030472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2031472f9654STobias Grosser }; 2032472f9654STobias Grosser 2033472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 2034472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2035472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 2036472f9654STobias Grosser } 2037472f9654STobias Grosser 2038472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 2039472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2040472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 2041472f9654STobias Grosser } 2042472f9654STobias Grosser } 2043472f9654STobias Grosser 20442f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 20452f3073b5SPhilipp Schaad const char *GroupName[3] = {"__gen_ocl_get_group_id0", 20462f3073b5SPhilipp Schaad "__gen_ocl_get_group_id1", 20472f3073b5SPhilipp Schaad "__gen_ocl_get_group_id2"}; 20482f3073b5SPhilipp Schaad 20492f3073b5SPhilipp Schaad const char *LocalName[3] = {"__gen_ocl_get_local_id0", 20502f3073b5SPhilipp Schaad "__gen_ocl_get_local_id1", 20512f3073b5SPhilipp Schaad "__gen_ocl_get_local_id2"}; 20522f3073b5SPhilipp Schaad 20532f3073b5SPhilipp Schaad auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 20542f3073b5SPhilipp Schaad Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 20552f3073b5SPhilipp Schaad Function *FN = M->getFunction(Name); 20562f3073b5SPhilipp Schaad 20572f3073b5SPhilipp Schaad // If FN is not available, declare it. 20582f3073b5SPhilipp Schaad if (!FN) { 20592f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 20602f3073b5SPhilipp Schaad std::vector<Type *> Args; 20612f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 20622f3073b5SPhilipp Schaad FN = Function::Create(Ty, Linkage, Name, M); 20632f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_FUNC); 20642f3073b5SPhilipp Schaad } 20652f3073b5SPhilipp Schaad 20662f3073b5SPhilipp Schaad Value *Val = Builder.CreateCall(FN, {}); 20672f3073b5SPhilipp Schaad Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 20682f3073b5SPhilipp Schaad IDToValue[Id] = Val; 20692f3073b5SPhilipp Schaad KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 20702f3073b5SPhilipp Schaad }; 20712f3073b5SPhilipp Schaad 20722f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_grid; ++i) 20732f3073b5SPhilipp Schaad createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 20742f3073b5SPhilipp Schaad 20752f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_block; ++i) 20762f3073b5SPhilipp Schaad createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 20772f3073b5SPhilipp Schaad } 20782f3073b5SPhilipp Schaad 207900bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 208000bb5a99STobias Grosser auto Arg = FN->arg_begin(); 208100bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 208200bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 208300bb5a99STobias Grosser continue; 208400bb5a99STobias Grosser 208500bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2086206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2087206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 208800bb5a99STobias Grosser isl_id_free(Id); 208900bb5a99STobias Grosser 209000bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 209100bb5a99STobias Grosser Arg++; 209200bb5a99STobias Grosser continue; 209300bb5a99STobias Grosser } 209400bb5a99STobias Grosser 2095fe74a7a1STobias Grosser Value *Val = &*Arg; 2096fe74a7a1STobias Grosser 2097fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 209800bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 2099fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2100fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 2101fe74a7a1STobias Grosser } 2102fe74a7a1STobias Grosser 2103fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 210400bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 210500bb5a99STobias Grosser 210600bb5a99STobias Grosser Arg++; 210700bb5a99STobias Grosser } 210800bb5a99STobias Grosser } 210900bb5a99STobias Grosser 211051dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 211151dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 211251dfc275STobias Grosser auto Arg = FN->arg_begin(); 211351dfc275STobias Grosser 211451dfc275STobias Grosser bool StoredScalar = false; 211551dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 211651dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 211751dfc275STobias Grosser continue; 211851dfc275STobias Grosser 211951dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2120206e9e3bSTobias Grosser const ScopArrayInfo *SAI = 2121206e9e3bSTobias Grosser ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 212251dfc275STobias Grosser isl_id_free(Id); 212351dfc275STobias Grosser 212451dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 212551dfc275STobias Grosser Arg++; 212651dfc275STobias Grosser continue; 212751dfc275STobias Grosser } 212851dfc275STobias Grosser 212951dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 213051dfc275STobias Grosser Arg++; 213151dfc275STobias Grosser continue; 213251dfc275STobias Grosser } 213351dfc275STobias Grosser 213451dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 213551dfc275STobias Grosser Value *ArgPtr = &*Arg; 213651dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 213751dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 213851dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 213951dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 214051dfc275STobias Grosser StoredScalar = true; 214151dfc275STobias Grosser 214251dfc275STobias Grosser Arg++; 214351dfc275STobias Grosser } 214451dfc275STobias Grosser 2145638316daSSiddharth Bhat if (StoredScalar) { 214651dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 214751dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 214851dfc275STobias Grosser /// To support this case we need to store these scalars back at each 214951dfc275STobias Grosser /// memory store or at least before each kernel barrier. 2150638316daSSiddharth Bhat if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 215151dfc275STobias Grosser BuildSuccessful = 0; 2152638316daSSiddharth Bhat DEBUG( 2153638316daSSiddharth Bhat dbgs() << getUniqueScopName(&S) 2154638316daSSiddharth Bhat << " has a store to a scalar value that" 2155638316daSSiddharth Bhat " would be undefined to run in parallel. Bailing out.\n";); 2156638316daSSiddharth Bhat } 2157638316daSSiddharth Bhat } 215851dfc275STobias Grosser } 215951dfc275STobias Grosser 2160b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2161b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2162b513b491STobias Grosser 2163b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 2164b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 2165b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2166206e9e3bSTobias Grosser Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2167b513b491STobias Grosser 2168f919d8b3STobias Grosser Type *ArrayTy = EleTy; 2169b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 2170b513b491STobias Grosser 2171f5aff704SRoman Gareev Sizes.push_back(nullptr); 2172928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2173b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2174f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 2175b513b491STobias Grosser isl_val_free(Val); 2176b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2177928d7573STobias Grosser } 2178928d7573STobias Grosser 2179928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 2180928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2181928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 2182928d7573STobias Grosser isl_val_free(Val); 2183b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 2184b513b491STobias Grosser } 2185b513b491STobias Grosser 2186130ca30fSTobias Grosser const ScopArrayInfo *SAI; 2187130ca30fSTobias Grosser Value *Allocation; 2188130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 2189130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 2190130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2191130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2192130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2193f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2194f919d8b3STobias Grosser 2195130ca30fSTobias Grosser Allocation = GlobalVar; 2196130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 2197130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2198130ca30fSTobias Grosser } else { 2199130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 2200130ca30fSTobias Grosser } 22014d5a9172STobias Grosser SAI = 22024d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2203b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2204130ca30fSTobias Grosser IDToValue[Id] = Allocation; 2205130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 2206b513b491STobias Grosser KernelIds.push_back(Id); 2207b513b491STobias Grosser IDToSAI[Id] = SAI; 2208b513b491STobias Grosser } 2209b513b491STobias Grosser } 2210b513b491STobias Grosser 2211f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 2212f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2213f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 221479f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 221532837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 221617f01968SSiddharth Bhat 221717f01968SSiddharth Bhat switch (Arch) { 221817f01968SSiddharth Bhat case GPUArch::NVPTX64: 221917f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 222032837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 222117f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 222217f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 222332837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 222417f01968SSiddharth Bhat break; 22252f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22262f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 22272f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 22282f3073b5SPhilipp Schaad break; 22292f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22302f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 22312f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 22322f3073b5SPhilipp Schaad break; 223317f01968SSiddharth Bhat } 223432837fe3STobias Grosser 2235edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 223632837fe3STobias Grosser 223759ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 223832837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 223932837fe3STobias Grosser 224059ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 224159ab0705STobias Grosser 224232837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 224332837fe3STobias Grosser Builder.CreateRetVoid(); 224432837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2245472f9654STobias Grosser 2246629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 2247629109b6STobias Grosser 224800bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2249b513b491STobias Grosser createKernelVariables(Kernel, FN); 22502f3073b5SPhilipp Schaad 22512f3073b5SPhilipp Schaad switch (Arch) { 22522f3073b5SPhilipp Schaad case GPUArch::NVPTX64: 2253472f9654STobias Grosser insertKernelIntrinsics(Kernel); 22542f3073b5SPhilipp Schaad break; 22552f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22562f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22572f3073b5SPhilipp Schaad insertKernelCallsSPIR(Kernel); 22582f3073b5SPhilipp Schaad break; 22592f3073b5SPhilipp Schaad } 226032837fe3STobias Grosser } 226132837fe3STobias Grosser 226274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 226317f01968SSiddharth Bhat llvm::Triple GPUTriple; 226417f01968SSiddharth Bhat 226517f01968SSiddharth Bhat switch (Arch) { 226617f01968SSiddharth Bhat case GPUArch::NVPTX64: 226717f01968SSiddharth Bhat switch (Runtime) { 226817f01968SSiddharth Bhat case GPURuntime::CUDA: 226917f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 227017f01968SSiddharth Bhat break; 227117f01968SSiddharth Bhat case GPURuntime::OpenCL: 227217f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 227317f01968SSiddharth Bhat break; 227417f01968SSiddharth Bhat } 227517f01968SSiddharth Bhat break; 22762f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22772f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22782f3073b5SPhilipp Schaad std::string SPIRAssembly; 22792f3073b5SPhilipp Schaad raw_string_ostream IROstream(SPIRAssembly); 22802f3073b5SPhilipp Schaad IROstream << *GPUModule; 22812f3073b5SPhilipp Schaad IROstream.flush(); 22822f3073b5SPhilipp Schaad return SPIRAssembly; 228317f01968SSiddharth Bhat } 228417f01968SSiddharth Bhat 228574dc3cb4STobias Grosser std::string ErrMsg; 228674dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 228774dc3cb4STobias Grosser 228874dc3cb4STobias Grosser if (!GPUTarget) { 228974dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 229074dc3cb4STobias Grosser return ""; 229174dc3cb4STobias Grosser } 229274dc3cb4STobias Grosser 229374dc3cb4STobias Grosser TargetOptions Options; 229474dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 229517f01968SSiddharth Bhat 229617f01968SSiddharth Bhat std::string subtarget; 229717f01968SSiddharth Bhat 229817f01968SSiddharth Bhat switch (Arch) { 229917f01968SSiddharth Bhat case GPUArch::NVPTX64: 230017f01968SSiddharth Bhat subtarget = CudaVersion; 230117f01968SSiddharth Bhat break; 23022f3073b5SPhilipp Schaad case GPUArch::SPIR32: 23032f3073b5SPhilipp Schaad case GPUArch::SPIR64: 23042f3073b5SPhilipp Schaad llvm_unreachable("No subtarget for SPIR architecture"); 230517f01968SSiddharth Bhat } 230617f01968SSiddharth Bhat 230717f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 230817f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 230974dc3cb4STobias Grosser 231074dc3cb4STobias Grosser SmallString<0> ASMString; 231174dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 231274dc3cb4STobias Grosser llvm::legacy::PassManager PM; 231374dc3cb4STobias Grosser 231474dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 231574dc3cb4STobias Grosser 231674dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 231774dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 231874dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 231974dc3cb4STobias Grosser return ""; 232074dc3cb4STobias Grosser } 232174dc3cb4STobias Grosser 232274dc3cb4STobias Grosser PM.run(*GPUModule); 232374dc3cb4STobias Grosser 232474dc3cb4STobias Grosser return ASMStream.str(); 232574dc3cb4STobias Grosser } 232674dc3cb4STobias Grosser 23278fc6cdfbSTobias Grosser bool GPUNodeBuilder::requiresCUDALibDevice() { 23285b307cdbSTobias Grosser bool RequiresLibDevice = false; 23298fc6cdfbSTobias Grosser for (Function &F : GPUModule->functions()) { 23308fc6cdfbSTobias Grosser if (!F.isDeclaration()) 23318fc6cdfbSTobias Grosser continue; 23328fc6cdfbSTobias Grosser 23338fc6cdfbSTobias Grosser std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F); 23348fc6cdfbSTobias Grosser if (CUDALibDeviceFunc.length() != 0) { 23358fc6cdfbSTobias Grosser F.setName(CUDALibDeviceFunc); 23365b307cdbSTobias Grosser RequiresLibDevice = true; 23378fc6cdfbSTobias Grosser } 23388fc6cdfbSTobias Grosser } 23398fc6cdfbSTobias Grosser 23405b307cdbSTobias Grosser return RequiresLibDevice; 23418fc6cdfbSTobias Grosser } 23428fc6cdfbSTobias Grosser 23438fc6cdfbSTobias Grosser void GPUNodeBuilder::addCUDALibDevice() { 23448fc6cdfbSTobias Grosser if (Arch != GPUArch::NVPTX64) 23458fc6cdfbSTobias Grosser return; 23468fc6cdfbSTobias Grosser 23478fc6cdfbSTobias Grosser if (requiresCUDALibDevice()) { 23488fc6cdfbSTobias Grosser SMDiagnostic Error; 23498fc6cdfbSTobias Grosser 23508fc6cdfbSTobias Grosser errs() << CUDALibDevice << "\n"; 23518fc6cdfbSTobias Grosser auto LibDeviceModule = 23528fc6cdfbSTobias Grosser parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 23538fc6cdfbSTobias Grosser 23548fc6cdfbSTobias Grosser if (!LibDeviceModule) { 23558fc6cdfbSTobias Grosser BuildSuccessful = false; 23568fc6cdfbSTobias Grosser report_fatal_error("Could not find or load libdevice. Skipping GPU " 23578fc6cdfbSTobias Grosser "kernel generation. Please set -polly-acc-libdevice " 23588fc6cdfbSTobias Grosser "accordingly.\n"); 23598fc6cdfbSTobias Grosser return; 23608fc6cdfbSTobias Grosser } 23618fc6cdfbSTobias Grosser 23628fc6cdfbSTobias Grosser Linker L(*GPUModule); 23638fc6cdfbSTobias Grosser 23648fc6cdfbSTobias Grosser // Set an nvptx64 target triple to avoid linker warnings. The original 23658fc6cdfbSTobias Grosser // triple of the libdevice files are nvptx-unknown-unknown. 23668fc6cdfbSTobias Grosser LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 23678fc6cdfbSTobias Grosser L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 23688fc6cdfbSTobias Grosser } 23698fc6cdfbSTobias Grosser } 23708fc6cdfbSTobias Grosser 237157793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 237265d7f72fSSiddharth Bhat 23735857b701STobias Grosser if (verifyModule(*GPUModule)) { 237465d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 237565d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2376a0fb8b23SSiddharth Bhat DEBUG(dbgs() << "verifyModule Error:\n"; 2377a0fb8b23SSiddharth Bhat verifyModule(*GPUModule, &dbgs());); 237865d7f72fSSiddharth Bhat 237965d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 238065d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 238165d7f72fSSiddharth Bhat 23825857b701STobias Grosser BuildSuccessful = false; 23835857b701STobias Grosser return ""; 23845857b701STobias Grosser } 238532837fe3STobias Grosser 23868fc6cdfbSTobias Grosser addCUDALibDevice(); 23878fc6cdfbSTobias Grosser 238832837fe3STobias Grosser if (DumpKernelIR) 238932837fe3STobias Grosser outs() << *GPUModule << "\n"; 239032837fe3STobias Grosser 23912f3073b5SPhilipp Schaad if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 23929a18d559STobias Grosser // Optimize module. 23939a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 23949a18d559STobias Grosser PassManagerBuilder PassBuilder; 23959a18d559STobias Grosser PassBuilder.OptLevel = 3; 23969a18d559STobias Grosser PassBuilder.SizeLevel = 0; 23979a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 23989a18d559STobias Grosser OptPasses.run(*GPUModule); 23992f3073b5SPhilipp Schaad } 24009a18d559STobias Grosser 240174dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 240274dc3cb4STobias Grosser 240374dc3cb4STobias Grosser if (DumpKernelASM) 240474dc3cb4STobias Grosser outs() << Assembly << "\n"; 240574dc3cb4STobias Grosser 240632837fe3STobias Grosser GPUModule.release(); 2407472f9654STobias Grosser KernelIDs.clear(); 240857793596STobias Grosser 240957793596STobias Grosser return Assembly; 241032837fe3STobias Grosser } 2411eadf76d3SSiddharth Bhat /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2412eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions to create an 2413eadf76d3SSiddharth Bhat /// `isl_pw_aff_list` from. We expect an rvalue ref because 2414eadf76d3SSiddharth Bhat /// all the isl_pw_aff are used up by this function. 2415eadf76d3SSiddharth Bhat /// 2416eadf76d3SSiddharth Bhat /// @returns The `isl_pw_aff_list`. 2417eadf76d3SSiddharth Bhat __isl_give isl_pw_aff_list * 2418eadf76d3SSiddharth Bhat createPwAffList(isl_ctx *Context, 2419eadf76d3SSiddharth Bhat const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2420eadf76d3SSiddharth Bhat isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2421eadf76d3SSiddharth Bhat 2422eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2423eadf76d3SSiddharth Bhat List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2424eadf76d3SSiddharth Bhat } 2425eadf76d3SSiddharth Bhat return List; 2426eadf76d3SSiddharth Bhat } 2427eadf76d3SSiddharth Bhat 2428eadf76d3SSiddharth Bhat /// Align all the `PwAffs` such that they have the same parameter dimensions. 2429eadf76d3SSiddharth Bhat /// 2430eadf76d3SSiddharth Bhat /// We loop over all `pw_aff` and align all of their spaces together to 2431eadf76d3SSiddharth Bhat /// create a common space for all the `pw_aff`. This common space is the 2432eadf76d3SSiddharth Bhat /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2433eadf76d3SSiddharth Bhat /// with the given `SeedSpace`. 2434eadf76d3SSiddharth Bhat /// @param PwAffs The list of piecewise affine functions we want to align. 2435eadf76d3SSiddharth Bhat /// This is an rvalue reference because the entire vector is 2436eadf76d3SSiddharth Bhat /// used up by the end of the operation. 2437eadf76d3SSiddharth Bhat /// @param SeedSpace The space to start the alignment process with. 2438eadf76d3SSiddharth Bhat /// @returns A std::pair, whose first element is the aligned space, 2439eadf76d3SSiddharth Bhat /// whose second element is the vector of aligned piecewise 2440eadf76d3SSiddharth Bhat /// affines. 2441eadf76d3SSiddharth Bhat static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2442eadf76d3SSiddharth Bhat alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2443eadf76d3SSiddharth Bhat __isl_take isl_space *SeedSpace) { 2444eadf76d3SSiddharth Bhat assert(SeedSpace && "Invalid seed space given."); 2445eadf76d3SSiddharth Bhat 2446eadf76d3SSiddharth Bhat isl_space *AlignSpace = SeedSpace; 2447eadf76d3SSiddharth Bhat for (isl_pw_aff *PwAff : PwAffs) { 2448eadf76d3SSiddharth Bhat isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2449eadf76d3SSiddharth Bhat AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2450eadf76d3SSiddharth Bhat } 2451eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AdjustedPwAffs; 2452eadf76d3SSiddharth Bhat 2453eadf76d3SSiddharth Bhat for (unsigned i = 0; i < PwAffs.size(); i++) { 2454eadf76d3SSiddharth Bhat isl_pw_aff *Adjusted = PwAffs[i]; 2455eadf76d3SSiddharth Bhat assert(Adjusted && "Invalid pw_aff given."); 2456eadf76d3SSiddharth Bhat Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2457eadf76d3SSiddharth Bhat AdjustedPwAffs.push_back(Adjusted); 2458eadf76d3SSiddharth Bhat } 2459eadf76d3SSiddharth Bhat return std::make_pair(AlignSpace, AdjustedPwAffs); 2460eadf76d3SSiddharth Bhat } 246132837fe3STobias Grosser 24629dfe4e7cSTobias Grosser namespace { 24639dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 24649dfe4e7cSTobias Grosser public: 24659dfe4e7cSTobias Grosser static char ID; 24669dfe4e7cSTobias Grosser 246717f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 246817f01968SSiddharth Bhat 246917f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 247017f01968SSiddharth Bhat 2471e938517eSTobias Grosser /// The scop that is currently processed. 2472e938517eSTobias Grosser Scop *S; 2473e938517eSTobias Grosser 247438fc0aedSTobias Grosser LoopInfo *LI; 247538fc0aedSTobias Grosser DominatorTree *DT; 247638fc0aedSTobias Grosser ScalarEvolution *SE; 247738fc0aedSTobias Grosser const DataLayout *DL; 247838fc0aedSTobias Grosser RegionInfo *RI; 247938fc0aedSTobias Grosser 24809dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 24819dfe4e7cSTobias Grosser 2482e938517eSTobias Grosser /// Construct compilation options for PPCG. 2483e938517eSTobias Grosser /// 2484e938517eSTobias Grosser /// @returns The compilation options. 2485e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2486e938517eSTobias Grosser auto DebugOptions = 2487e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2488e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2489e938517eSTobias Grosser 2490e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2491e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2492e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2493e938517eSTobias Grosser DebugOptions->dump_sizes = false; 24948950ceadSTobias Grosser DebugOptions->verbose = false; 2495e938517eSTobias Grosser 2496e938517eSTobias Grosser Options->debug = DebugOptions; 2497e938517eSTobias Grosser 24989e3db2b7SSiddharth Bhat Options->group_chains = false; 2499e938517eSTobias Grosser Options->reschedule = true; 2500e938517eSTobias Grosser Options->scale_tile_loops = false; 2501e938517eSTobias Grosser Options->wrap = false; 2502e938517eSTobias Grosser 2503e938517eSTobias Grosser Options->non_negative_parameters = false; 2504e938517eSTobias Grosser Options->ctx = nullptr; 2505e938517eSTobias Grosser Options->sizes = nullptr; 2506e938517eSTobias Grosser 25079e3db2b7SSiddharth Bhat Options->tile = true; 25084eaedde5STobias Grosser Options->tile_size = 32; 25094eaedde5STobias Grosser 25109e3db2b7SSiddharth Bhat Options->isolate_full_tiles = false; 25119e3db2b7SSiddharth Bhat 2512130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2513b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2514b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2515e938517eSTobias Grosser 2516e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2517e938517eSTobias Grosser Options->openmp = false; 2518e938517eSTobias Grosser Options->linearize_device_arrays = true; 25199e3db2b7SSiddharth Bhat Options->allow_gnu_extensions = false; 2520e938517eSTobias Grosser 25219e3db2b7SSiddharth Bhat Options->unroll_copy_shared = false; 25229e3db2b7SSiddharth Bhat Options->unroll_gpu_tile = false; 25239e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25249e3db2b7SSiddharth Bhat 25259e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 25269e3db2b7SSiddharth Bhat Options->hybrid = false; 2527e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2528e938517eSTobias Grosser Options->opencl_use_gpu = false; 2529e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2530e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2531e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2532e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2533e938517eSTobias Grosser 2534e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2535e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2536e938517eSTobias Grosser 2537e938517eSTobias Grosser return Options; 2538e938517eSTobias Grosser } 2539e938517eSTobias Grosser 2540f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2541f384594dSTobias Grosser /// 2542f384594dSTobias Grosser /// Instead of a normal access of the form: 2543f384594dSTobias Grosser /// 2544f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2545f384594dSTobias Grosser /// 2546f384594dSTobias Grosser /// a tagged access has the form 2547f384594dSTobias Grosser /// 2548f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2549f384594dSTobias Grosser /// 2550f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2551f384594dSTobias Grosser /// triggered the access. 2552f384594dSTobias Grosser /// 2553f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2554f384594dSTobias Grosser /// 2555f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2556f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2557b65ccc43STobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release()); 2558f384594dSTobias Grosser 2559f384594dSTobias Grosser for (auto &Stmt : *S) 2560f384594dSTobias Grosser for (auto &Acc : Stmt) 2561f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 25621515f6b9STobias Grosser isl_map *Relation = Acc->getAccessRelation().release(); 2563dcf8d696STobias Grosser Relation = 2564dcf8d696STobias Grosser isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2565f384594dSTobias Grosser 2566f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2567f384594dSTobias Grosser Space = isl_space_range(Space); 2568f384594dSTobias Grosser Space = isl_space_from_range(Space); 2569fe46c3ffSTobias Grosser Space = 2570fe46c3ffSTobias Grosser isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2571f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2572f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2573f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2574f384594dSTobias Grosser } 2575f384594dSTobias Grosser 2576f384594dSTobias Grosser return Accesses; 2577f384594dSTobias Grosser } 2578f384594dSTobias Grosser 2579f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2580f384594dSTobias Grosser /// 2581f384594dSTobias Grosser /// @see getTaggedAccesses 2582f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2583f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2584f384594dSTobias Grosser } 2585f384594dSTobias Grosser 2586f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2587f384594dSTobias Grosser /// 2588f384594dSTobias Grosser /// @see getTaggedAccesses 2589f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2590f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2591f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2592f384594dSTobias Grosser } 2593f384594dSTobias Grosser 2594f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2595f384594dSTobias Grosser /// 2596f384594dSTobias Grosser /// @see getTaggedAccesses 2597f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2598f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2599f384594dSTobias Grosser } 2600f384594dSTobias Grosser 2601aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2602aef5196fSTobias Grosser /// 2603aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2604aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2605aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2606aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2607aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2608aef5196fSTobias Grosser /// the data format that ppcg expects. 2609aef5196fSTobias Grosser /// 2610aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2611aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2612aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2613bd81a7eeSTobias Grosser S->getIslCtx(), 2614bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2615aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2616aef5196fSTobias Grosser 261725271b91STobias Grosser for (const SCEV *P : S->parameters()) { 26189a63570bSTobias Grosser isl_id *Id = S->getIdForParam(P).release(); 2619aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2620aef5196fSTobias Grosser } 2621aef5196fSTobias Grosser 2622aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 262377eef90fSTobias Grosser auto Id = Array->getBasePtrId().release(); 2624aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2625aef5196fSTobias Grosser } 2626aef5196fSTobias Grosser 2627aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2628aef5196fSTobias Grosser 2629aef5196fSTobias Grosser return Names; 2630aef5196fSTobias Grosser } 2631aef5196fSTobias Grosser 2632e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2633e938517eSTobias Grosser /// 2634f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2635f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2636f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2637f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2638e938517eSTobias Grosser /// 2639e938517eSTobias Grosser /// @returns A new ppcg scop. 2640e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 26419e3db2b7SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 26429e3db2b7SSiddharth Bhat 2643e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2644e938517eSTobias Grosser 2645e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2646a82f2d26SSiddharth Bhat // enable live range reordering 2647a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2648e938517eSTobias Grosser 2649e938517eSTobias Grosser PPCGScop->start = 0; 2650e938517eSTobias Grosser PPCGScop->end = 0; 2651e938517eSTobias Grosser 26528ea1fc19STobias Grosser PPCGScop->context = S->getContext().release(); 265331df6f31STobias Grosser PPCGScop->domain = S->getDomains().release(); 26549e3db2b7SSiddharth Bhat // TODO: investigate this further. PPCG calls collect_call_domains. 26558ea1fc19STobias Grosser PPCGScop->call = isl_union_set_from_set(S->getContext().release()); 2656f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 26575ab39ff2STobias Grosser PPCGScop->reads = S->getReads().release(); 2658e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2659f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 26605ab39ff2STobias Grosser PPCGScop->may_writes = S->getWrites().release(); 2661f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 26625ab39ff2STobias Grosser PPCGScop->must_writes = S->getMustWrites().release(); 2663e938517eSTobias Grosser PPCGScop->live_out = nullptr; 26649e3db2b7SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 26659e3db2b7SSiddharth Bhat PPCGScop->must_kills = KillsInfo.MustKills.take(); 26669e3db2b7SSiddharth Bhat 2667e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2668a82f2d26SSiddharth Bhat PPCGScop->independence = 2669a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2670e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2671e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2672e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2673e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2674e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2675e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2676e938517eSTobias Grosser 267761bd3a48STobias Grosser PPCGScop->schedule = S->getScheduleTree().release(); 2678a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2679a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2680a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2681a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2682a82f2d26SSiddharth Bhat 2683a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2684e938517eSTobias Grosser PPCGScop->pet = nullptr; 2685e938517eSTobias Grosser 2686f384594dSTobias Grosser compute_tagger(PPCGScop); 2687f384594dSTobias Grosser compute_dependences(PPCGScop); 26889e3db2b7SSiddharth Bhat eliminate_dead_code(PPCGScop); 2689f384594dSTobias Grosser 2690e938517eSTobias Grosser return PPCGScop; 2691e938517eSTobias Grosser } 2692e938517eSTobias Grosser 2693a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 269460f63b49STobias Grosser /// 269560f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 269660f63b49STobias Grosser /// 269760f63b49STobias Grosser /// @returns A list of array accesses. 269860f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 269960f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 270060f63b49STobias Grosser 270160f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 270260f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 270360f63b49STobias Grosser Access->read = Acc->isRead(); 270460f63b49STobias Grosser Access->write = Acc->isWrite(); 27051515f6b9STobias Grosser Access->access = Acc->getAccessRelation().release(); 270660f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 270760f63b49STobias Grosser Space = isl_space_range(Space); 270860f63b49STobias Grosser Space = isl_space_from_range(Space); 2709fe46c3ffSTobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 271060f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 271160f63b49STobias Grosser Access->tagged_access = 27121515f6b9STobias Grosser isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2713b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 2714fe46c3ffSTobias Grosser Access->ref_id = Acc->getId().release(); 271560f63b49STobias Grosser Access->next = Accesses; 2716b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 271760f63b49STobias Grosser Accesses = Access; 271860f63b49STobias Grosser } 271960f63b49STobias Grosser 272060f63b49STobias Grosser return Accesses; 272160f63b49STobias Grosser } 272260f63b49STobias Grosser 272369b46751STobias Grosser /// Collect the list of GPU statements. 272469b46751STobias Grosser /// 272569b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 272669b46751STobias Grosser /// as well as a list with all memory accesses. 272769b46751STobias Grosser /// 272869b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 272969b46751STobias Grosser /// 273069b46751STobias Grosser /// @returns A linked-list of statements. 273169b46751STobias Grosser gpu_stmt *getStatements() { 273269b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 273369b46751STobias Grosser std::distance(S->begin(), S->end())); 273469b46751STobias Grosser 273569b46751STobias Grosser int i = 0; 273669b46751STobias Grosser for (auto &Stmt : *S) { 273769b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 273869b46751STobias Grosser 2739dcf8d696STobias Grosser GPUStmt->id = Stmt.getDomainId().release(); 274069b46751STobias Grosser 274169b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 274269b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 274360f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 274469b46751STobias Grosser i++; 274569b46751STobias Grosser } 274669b46751STobias Grosser 274769b46751STobias Grosser return Stmts; 274869b46751STobias Grosser } 274969b46751STobias Grosser 275060f63b49STobias Grosser /// Derive the extent of an array. 275160f63b49STobias Grosser /// 2752d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2753d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2754d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2755d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2756d58acf86STobias Grosser /// subscript value for the first dimension. 275760f63b49STobias Grosser /// 275860f63b49STobias Grosser /// @param Array The array to derive the extent for. 275960f63b49STobias Grosser /// 276060f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 276160f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2762d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 27635ab39ff2STobias Grosser isl_union_map *Accesses = S->getAccesses().release(); 276431df6f31STobias Grosser Accesses = 276531df6f31STobias Grosser isl_union_map_intersect_domain(Accesses, S->getDomains().release()); 2766d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 276760f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2768d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2769d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2770d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2771d58acf86STobias Grosser 2772d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2773d58acf86STobias Grosser isl_union_set_free(AccessUSet); 277477eef90fSTobias Grosser return isl_set_empty(Array->getSpace().release()); 2775d58acf86STobias Grosser } 2776d58acf86STobias Grosser 2777d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2778d58acf86STobias Grosser isl_union_set_free(AccessUSet); 277977eef90fSTobias Grosser return isl_set_universe(Array->getSpace().release()); 2780d58acf86STobias Grosser } 2781d58acf86STobias Grosser 278260f63b49STobias Grosser isl_set *AccessSet = 278377eef90fSTobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace().release()); 278460f63b49STobias Grosser 2785d58acf86STobias Grosser isl_union_set_free(AccessUSet); 278677eef90fSTobias Grosser isl_local_space *LS = 278777eef90fSTobias Grosser isl_local_space_from_space(Array->getSpace().release()); 2788d58acf86STobias Grosser 2789d58acf86STobias Grosser isl_pw_aff *Val = 2790d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2791d58acf86STobias Grosser 2792d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2793d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2794d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2795d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2796d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2797d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 279877eef90fSTobias Grosser OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, 279977eef90fSTobias Grosser Array->getBasePtrId().release()); 280077eef90fSTobias Grosser OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, 280177eef90fSTobias Grosser Array->getBasePtrId().release()); 2802d58acf86STobias Grosser 280377eef90fSTobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace().release()); 2804d58acf86STobias Grosser 2805d58acf86STobias Grosser Extent = isl_set_intersect( 2806d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2807d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2808d58acf86STobias Grosser 2809d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2810d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2811d58acf86STobias Grosser 2812b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2813d58acf86STobias Grosser isl_pw_aff *PwAff = 281477eef90fSTobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release()); 2815b7f68b8cSSiddharth Bhat 2816b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2817b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2818b7f68b8cSSiddharth Bhat if (!PwAff) { 2819b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2820b7f68b8cSSiddharth Bhat continue; 2821b7f68b8cSSiddharth Bhat } 2822b7f68b8cSSiddharth Bhat 2823d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 282477eef90fSTobias Grosser isl_local_space_from_space(Array->getSpace().release()), isl_dim_set, 282577eef90fSTobias Grosser i)); 2826d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2827d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2828d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2829d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2830d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2831d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2832d58acf86STobias Grosser } 2833d58acf86STobias Grosser 2834d58acf86STobias Grosser return Extent; 283560f63b49STobias Grosser } 283660f63b49STobias Grosser 283760f63b49STobias Grosser /// Derive the bounds of an array. 283860f63b49STobias Grosser /// 283960f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 284060f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 284160f63b49STobias Grosser /// ScopArrayInfo. 284260f63b49STobias Grosser /// 284360f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 284460f63b49STobias Grosser /// @param Array The polly array from which to take the information. 284560f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2846eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> Bounds; 28479e3db2b7SSiddharth Bhat 284860f63b49STobias Grosser if (PPCGArray.n_index > 0) { 284902293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 285002293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 285102293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 285202293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 285302293ed7STobias Grosser isl_set_free(Dom); 28549e3db2b7SSiddharth Bhat isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2855eadf76d3SSiddharth Bhat Bounds.push_back(Zero); 285602293ed7STobias Grosser } else { 285760f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 285860f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 285960f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 286060f63b49STobias Grosser isl_set_free(Dom); 286160f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 286202293ed7STobias Grosser isl_local_space *LS = 286302293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 286460f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 286560f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 286660f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 28678ea1fc19STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext().release()); 2868eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 286960f63b49STobias Grosser } 287002293ed7STobias Grosser } 287160f63b49STobias Grosser 287260f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 287377eef90fSTobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 287460f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 287560f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 287660f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2877eadf76d3SSiddharth Bhat Bounds.push_back(Bound); 287860f63b49STobias Grosser } 28799e3db2b7SSiddharth Bhat 2880eadf76d3SSiddharth Bhat /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2881eadf76d3SSiddharth Bhat /// to have the same parameter dimensions. So, we need to align them to an 2882eadf76d3SSiddharth Bhat /// appropriate space. 2883eadf76d3SSiddharth Bhat /// Scop::Context is _not_ an appropriate space, because when we have 2884eadf76d3SSiddharth Bhat /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 2885eadf76d3SSiddharth Bhat /// contain all parameter dimensions. 2886eadf76d3SSiddharth Bhat /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 2887b65ccc43STobias Grosser isl_space *SeedAlignSpace = S->getParamSpace().release(); 2888eadf76d3SSiddharth Bhat SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 2889eadf76d3SSiddharth Bhat 2890eadf76d3SSiddharth Bhat isl_space *AlignSpace = nullptr; 2891eadf76d3SSiddharth Bhat std::vector<isl_pw_aff *> AlignedBounds; 2892eadf76d3SSiddharth Bhat std::tie(AlignSpace, AlignedBounds) = 2893eadf76d3SSiddharth Bhat alignPwAffs(std::move(Bounds), SeedAlignSpace); 2894eadf76d3SSiddharth Bhat 2895eadf76d3SSiddharth Bhat assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 2896eadf76d3SSiddharth Bhat 2897eadf76d3SSiddharth Bhat isl_pw_aff_list *BoundsList = 2898eadf76d3SSiddharth Bhat createPwAffList(S->getIslCtx(), std::move(AlignedBounds)); 2899eadf76d3SSiddharth Bhat 29009e3db2b7SSiddharth Bhat isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2901eadf76d3SSiddharth Bhat BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 29029e3db2b7SSiddharth Bhat 29039e3db2b7SSiddharth Bhat assert(BoundsSpace && "Unable to access space of array."); 29049e3db2b7SSiddharth Bhat assert(BoundsList && "Unable to access list of bounds."); 29059e3db2b7SSiddharth Bhat 29069e3db2b7SSiddharth Bhat PPCGArray.bound = 29079e3db2b7SSiddharth Bhat isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 29089e3db2b7SSiddharth Bhat assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 290960f63b49STobias Grosser } 291060f63b49STobias Grosser 291160f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 291260f63b49STobias Grosser /// 291360f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 291443f178bbSSiddharth Bhat void createArrays(gpu_prog *PPCGProg, 291543f178bbSSiddharth Bhat const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 291660f63b49STobias Grosser int i = 0; 291743f178bbSSiddharth Bhat for (auto &Array : ValidSAIs) { 291860f63b49STobias Grosser std::string TypeName; 291960f63b49STobias Grosser raw_string_ostream OS(TypeName); 292060f63b49STobias Grosser 292160f63b49STobias Grosser OS << *Array->getElementType(); 292260f63b49STobias Grosser TypeName = OS.str(); 292360f63b49STobias Grosser 292460f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 292560f63b49STobias Grosser 292677eef90fSTobias Grosser PPCGArray.space = Array->getSpace().release(); 292760f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 292834eeabbcSSiddharth Bhat PPCGArray.size = DL->getTypeAllocSize(Array->getElementType()); 292960f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 293060f63b49STobias Grosser PPCGArray.extent = nullptr; 293160f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 293260f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 293360f63b49STobias Grosser PPCGArray.n_ref = 0; 293460f63b49STobias Grosser PPCGArray.refs = nullptr; 293560f63b49STobias Grosser PPCGArray.accessed = true; 2936fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2937fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 293860f63b49STobias Grosser PPCGArray.has_compound_element = false; 293960f63b49STobias Grosser PPCGArray.local = false; 294060f63b49STobias Grosser PPCGArray.declare_local = false; 294160f63b49STobias Grosser PPCGArray.global = false; 294260f63b49STobias Grosser PPCGArray.linearize = false; 294360f63b49STobias Grosser PPCGArray.dep_order = nullptr; 294413c78e4dSTobias Grosser PPCGArray.user = Array; 294560f63b49STobias Grosser 29469e3db2b7SSiddharth Bhat PPCGArray.bound = nullptr; 294760f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 29482d010dafSTobias Grosser i++; 2949b9fc860aSTobias Grosser 2950b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 295160f63b49STobias Grosser } 295260f63b49STobias Grosser } 295360f63b49STobias Grosser 295460f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 295560f63b49STobias Grosser /// 295660f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 295760f63b49STobias Grosser isl_union_map *getArrayIdentity() { 2958b65ccc43STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release()); 295960f63b49STobias Grosser 2960d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 296177eef90fSTobias Grosser isl_space *Space = Array->getSpace().release(); 296260f63b49STobias Grosser Space = isl_space_map_from_set(Space); 296360f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 296460f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 296560f63b49STobias Grosser } 296660f63b49STobias Grosser 296760f63b49STobias Grosser return Maps; 296860f63b49STobias Grosser } 296960f63b49STobias Grosser 2970e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2971e938517eSTobias Grosser /// 2972a6d48f59SMichael Kruse /// @returns A new gpu program description. 2973e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2974e938517eSTobias Grosser 2975e938517eSTobias Grosser if (!PPCGScop) 2976e938517eSTobias Grosser return nullptr; 2977e938517eSTobias Grosser 2978e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2979e938517eSTobias Grosser 2980e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2981e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2982aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 298360f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 298460f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 298560f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 298660f63b49STobias Grosser PPCGProg->tagged_must_kill = 298760f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 298860f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 298960f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 29909e3db2b7SSiddharth Bhat // TODO: verify that this assignment is correct. 2991e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2992a82f2d26SSiddharth Bhat 2993a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2994a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2995a82f2d26SSiddharth Bhat // what the semantics of this is. 2996a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2997a82f2d26SSiddharth Bhat PPCGProg->array_order = 2998a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 299969b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 300069b46751STobias Grosser PPCGProg->stmts = getStatements(); 300143f178bbSSiddharth Bhat 300243f178bbSSiddharth Bhat // Only consider arrays that have a non-empty extent. 300343f178bbSSiddharth Bhat // Otherwise, this will cause us to consider the following kinds of 300443f178bbSSiddharth Bhat // empty arrays: 300543f178bbSSiddharth Bhat // 1. Invariant loads that are represented by SAI objects. 300643f178bbSSiddharth Bhat // 2. Arrays with statically known zero size. 300743f178bbSSiddharth Bhat auto ValidSAIsRange = 300843f178bbSSiddharth Bhat make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 300943f178bbSSiddharth Bhat return !isl::manage(getExtent(SAI)).is_empty(); 301043f178bbSSiddharth Bhat }); 301143f178bbSSiddharth Bhat SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 301243f178bbSSiddharth Bhat ValidSAIsRange.end()); 301343f178bbSSiddharth Bhat 301443f178bbSSiddharth Bhat PPCGProg->n_array = 301543f178bbSSiddharth Bhat ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 301660f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 301760f63b49STobias Grosser PPCGProg->n_array); 301860f63b49STobias Grosser 301943f178bbSSiddharth Bhat createArrays(PPCGProg, ValidSAIs); 3020e938517eSTobias Grosser 3021d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 3022e938517eSTobias Grosser return PPCGProg; 3023e938517eSTobias Grosser } 3024e938517eSTobias Grosser 302569b46751STobias Grosser struct PrintGPUUserData { 302669b46751STobias Grosser struct cuda_info *CudaInfo; 302769b46751STobias Grosser struct gpu_prog *PPCGProg; 302869b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 302969b46751STobias Grosser }; 303069b46751STobias Grosser 303169b46751STobias Grosser /// Print a user statement node in the host code. 303269b46751STobias Grosser /// 303369b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 303469b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 303569b46751STobias Grosser /// host ast. 303669b46751STobias Grosser /// 303769b46751STobias Grosser /// @param P The printer to print to 303869b46751STobias Grosser /// @param Options The printing options to use 303969b46751STobias Grosser /// @param Node The node to print 304069b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 304169b46751STobias Grosser /// expected to be of type PrintGPUUserData. 304269b46751STobias Grosser /// 304369b46751STobias Grosser /// @returns A printer to which the output has been printed. 304469b46751STobias Grosser static __isl_give isl_printer * 304569b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 304669b46751STobias Grosser __isl_take isl_ast_print_options *Options, 304769b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 304869b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 304969b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 305069b46751STobias Grosser 305169b46751STobias Grosser if (Id) { 305220251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 305320251734STobias Grosser 305420251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 305520251734STobias Grosser // otherwise try to call pet functionality that is not available in 305620251734STobias Grosser // Polly. 305720251734STobias Grosser if (IsUser) { 305820251734STobias Grosser P = isl_printer_start_line(P); 305920251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 306020251734STobias Grosser P = isl_printer_end_line(P); 306120251734STobias Grosser isl_id_free(Id); 306220251734STobias Grosser isl_ast_print_options_free(Options); 306320251734STobias Grosser return P; 306420251734STobias Grosser } 306520251734STobias Grosser 306669b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 306769b46751STobias Grosser isl_id_free(Id); 306869b46751STobias Grosser Data->Kernels.push_back(Kernel); 306969b46751STobias Grosser } 307069b46751STobias Grosser 307169b46751STobias Grosser return print_host_user(P, Options, Node, User); 307269b46751STobias Grosser } 307369b46751STobias Grosser 307469b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 307569b46751STobias Grosser /// 307669b46751STobias Grosser /// @param Kernel The kernel to print 307769b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 307869b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 307969b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 308069b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 308169b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 308269b46751STobias Grosser char *String = isl_printer_get_str(P); 308369b46751STobias Grosser printf("%s\n", String); 308469b46751STobias Grosser free(String); 308569b46751STobias Grosser isl_printer_free(P); 308669b46751STobias Grosser } 308769b46751STobias Grosser 308869b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 308969b46751STobias Grosser /// 309069b46751STobias Grosser /// @param Tree An AST describing GPU code 309169b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 309269b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 309369b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 309469b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 309569b46751STobias Grosser 309669b46751STobias Grosser PrintGPUUserData Data; 309769b46751STobias Grosser Data.PPCGProg = PPCGProg; 309869b46751STobias Grosser 309969b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 310069b46751STobias Grosser Options = 310169b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 310269b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 310369b46751STobias Grosser char *String = isl_printer_get_str(P); 310469b46751STobias Grosser printf("# host\n"); 310569b46751STobias Grosser printf("%s\n", String); 310669b46751STobias Grosser free(String); 310769b46751STobias Grosser isl_printer_free(P); 310869b46751STobias Grosser 310969b46751STobias Grosser for (auto Kernel : Data.Kernels) { 311069b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 311169b46751STobias Grosser printKernel(Kernel); 311269b46751STobias Grosser } 311369b46751STobias Grosser } 311469b46751STobias Grosser 3115f384594dSTobias Grosser // Generate a GPU program using PPCG. 3116f384594dSTobias Grosser // 3117f384594dSTobias Grosser // GPU mapping consists of multiple steps: 3118f384594dSTobias Grosser // 3119f384594dSTobias Grosser // 1) Compute new schedule for the program. 3120f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 3121f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 3122f384594dSTobias Grosser // 3123f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3124f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3125f384594dSTobias Grosser // strategy directly from this pass. 3126f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3127f384594dSTobias Grosser 3128f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 3129f384594dSTobias Grosser 3130f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 3131f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 3132f384594dSTobias Grosser PPCGGen->print = nullptr; 3133f384594dSTobias Grosser PPCGGen->print_user = nullptr; 313460c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3135f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 3136f384594dSTobias Grosser PPCGGen->tree = nullptr; 3137f384594dSTobias Grosser PPCGGen->types.n = 0; 3138f384594dSTobias Grosser PPCGGen->types.name = nullptr; 3139f384594dSTobias Grosser PPCGGen->sizes = nullptr; 3140f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 3141f384594dSTobias Grosser PPCGGen->kernel_id = 0; 3142f384594dSTobias Grosser 3143f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 3144f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3145f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 31462341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3147f384594dSTobias Grosser 3148f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 3149f384594dSTobias Grosser 3150aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 3151aef5196fSTobias Grosser 3152b5563c68STobias Grosser Schedule = 3153b5563c68STobias Grosser isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3154b5563c68STobias Grosser 315569b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 3156aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 3157638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3158638316daSSiddharth Bhat << " does not have permutable bands. Bailing out\n";); 315969b46751STobias Grosser } else { 3160aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 316169b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 316269b46751STobias Grosser } 3163aef5196fSTobias Grosser 3164f384594dSTobias Grosser if (DumpSchedule) { 3165f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 3166f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3167f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 3168f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 3169f384594dSTobias Grosser if (Schedule) 3170f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 3171f384594dSTobias Grosser else 3172f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 3173f384594dSTobias Grosser 3174f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 3175f384594dSTobias Grosser isl_printer_free(P); 3176f384594dSTobias Grosser } 3177f384594dSTobias Grosser 317869b46751STobias Grosser if (DumpCode) { 317969b46751STobias Grosser printf("Code\n"); 318069b46751STobias Grosser printf("====\n"); 318169b46751STobias Grosser if (PPCGGen->tree) 318269b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 318369b46751STobias Grosser else 318469b46751STobias Grosser printf("No code generated\n"); 318569b46751STobias Grosser } 318669b46751STobias Grosser 3187f384594dSTobias Grosser isl_schedule_free(Schedule); 3188f384594dSTobias Grosser 3189f384594dSTobias Grosser return PPCGGen; 3190f384594dSTobias Grosser } 3191f384594dSTobias Grosser 3192f384594dSTobias Grosser /// Free gpu_gen structure. 3193f384594dSTobias Grosser /// 3194f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 3195f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 3196f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 3197f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 3198f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 3199f384594dSTobias Grosser free(PPCGGen); 3200f384594dSTobias Grosser } 3201f384594dSTobias Grosser 3202b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 3203b307ed4dSTobias Grosser /// 3204b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 3205b307ed4dSTobias Grosser /// ourselves. 3206b307ed4dSTobias Grosser /// 3207b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 3208b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 3209b307ed4dSTobias Grosser free(PPCGScop->options->debug); 3210b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 3211b307ed4dSTobias Grosser free(PPCGScop->options); 3212b307ed4dSTobias Grosser PPCGScop->options = nullptr; 3213b307ed4dSTobias Grosser } 3214b307ed4dSTobias Grosser 321582f2af35STobias Grosser /// Approximate the number of points in the set. 321682f2af35STobias Grosser /// 321782f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 321882f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 321982f2af35STobias Grosser /// 322082f2af35STobias Grosser /// @param Set The set to count. 322182f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 322282f2af35STobias Grosser /// expression. 322382f2af35STobias Grosser /// 322482f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 322582f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 322682f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 322782f2af35STobias Grosser 322882f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 322982f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 323082f2af35STobias Grosser 323182f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 323282f2af35STobias Grosser Space = isl_space_params(Space); 323382f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 323482f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 323582f2af35STobias Grosser 323682f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 323782f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 323882f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 323982f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 324082f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 324182f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 324282f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 324382f2af35STobias Grosser } 324482f2af35STobias Grosser 324582f2af35STobias Grosser isl_set_free(Set); 324682f2af35STobias Grosser isl_pw_aff_free(OneAff); 324782f2af35STobias Grosser 324882f2af35STobias Grosser return Expr; 324982f2af35STobias Grosser } 325082f2af35STobias Grosser 325182f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 325282f2af35STobias Grosser /// statement. 325382f2af35STobias Grosser /// 325482f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 325582f2af35STobias Grosser /// instructions. 325682f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 325782f2af35STobias Grosser /// expression. 325882f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 325982f2af35STobias Grosser /// by @p Stmt. 326082f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 326182f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 3262dcf8d696STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 326382f2af35STobias Grosser 326482f2af35STobias Grosser long InstCount = 0; 326582f2af35STobias Grosser 326682f2af35STobias Grosser if (Stmt.isBlockStmt()) { 326782f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 326882f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 326982f2af35STobias Grosser } else { 327082f2af35STobias Grosser auto *R = Stmt.getRegion(); 327182f2af35STobias Grosser 327282f2af35STobias Grosser for (auto *BB : R->blocks()) { 327382f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 327482f2af35STobias Grosser } 327582f2af35STobias Grosser } 327682f2af35STobias Grosser 327782f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 327882f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 327982f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 328082f2af35STobias Grosser } 328182f2af35STobias Grosser 328282f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 328382f2af35STobias Grosser /// 328482f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 328582f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 328682f2af35STobias Grosser /// expression. 328782f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 328882f2af35STobias Grosser /// in @p S. 328982f2af35STobias Grosser __isl_give isl_ast_expr * 329082f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 329182f2af35STobias Grosser isl_ast_expr *Instructions; 329282f2af35STobias Grosser 329382f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 329482f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 329582f2af35STobias Grosser 329682f2af35STobias Grosser for (ScopStmt &Stmt : S) { 329782f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 329882f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 329982f2af35STobias Grosser } 330082f2af35STobias Grosser return Instructions; 330182f2af35STobias Grosser } 330282f2af35STobias Grosser 330382f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 330482f2af35STobias Grosser /// 330582f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 330682f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 330782f2af35STobias Grosser /// expression. 330882f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 330982f2af35STobias Grosser /// compute and to FALSE, otherwise. 331082f2af35STobias Grosser __isl_give isl_ast_expr * 331182f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 331282f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 331382f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 331482f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 331582f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 331682f2af35STobias Grosser } 331782f2af35STobias Grosser 3318f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 3319f291c8d5SSiddharth Bhat /// kernels. 3320f291c8d5SSiddharth Bhat /// 3321f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 3322f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 33238fc6cdfbSTobias Grosser bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 33248fc6cdfbSTobias Grosser bool AllowCUDALibDevice) { 3325f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 3326f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 33278fc6cdfbSTobias Grosser if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 33288fc6cdfbSTobias Grosser AllowCUDALibDevice)) { 3329f291c8d5SSiddharth Bhat continue; 3330f291c8d5SSiddharth Bhat } 3331f291c8d5SSiddharth Bhat 3332bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 3333bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3334bccaea57SSiddharth Bhat if (!p) 3335bccaea57SSiddharth Bhat continue; 3336bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 3337bccaea57SSiddharth Bhat return true; 3338bccaea57SSiddharth Bhat } 3339f291c8d5SSiddharth Bhat } 3340bccaea57SSiddharth Bhat return false; 3341bccaea57SSiddharth Bhat } 3342bccaea57SSiddharth Bhat 3343f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 33448fc6cdfbSTobias Grosser bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3345bccaea57SSiddharth Bhat for (auto &Stmt : S) { 3346bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 33478fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 33488fc6cdfbSTobias Grosser AllowCUDALibDevice)) 3349bccaea57SSiddharth Bhat return true; 3350bccaea57SSiddharth Bhat } else { 3351bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 3352bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 3353bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 33548fc6cdfbSTobias Grosser if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3355bccaea57SSiddharth Bhat return true; 3356bccaea57SSiddharth Bhat } 3357bccaea57SSiddharth Bhat } 3358bccaea57SSiddharth Bhat return false; 3359bccaea57SSiddharth Bhat } 3360bccaea57SSiddharth Bhat 336138fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 336238fc0aedSTobias Grosser /// 336332837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 336432837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 336532837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 336638fc0aedSTobias Grosser ScopAnnotator Annotator; 336738fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 336838fc0aedSTobias Grosser 336938fc0aedSTobias Grosser Region *R = &S->getRegion(); 337038fc0aedSTobias Grosser 337138fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 337238fc0aedSTobias Grosser 337338fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 337438fc0aedSTobias Grosser 337538fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 337638fc0aedSTobias Grosser 337738fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 337838fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 337938fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 338038fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 338138fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 338238fc0aedSTobias Grosser // code generating this scop. 338303346c27SSiddharth Bhat BBPair StartExitBlocks; 338403346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 338503346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 33862d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3387256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 338838fc0aedSTobias Grosser 338903346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 339003346c27SSiddharth Bhat 33912d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 339217f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 3393acf80064SEli Friedman 339438fc0aedSTobias Grosser // TODO: Handle LICM 339538fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 339638fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 3397cb1aef8dSTobias Grosser 3398cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 33992b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 340082f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 340182f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 3402cb1aef8dSTobias Grosser isl_ast_build_free(Build); 3403cb1aef8dSTobias Grosser 34049e3db2b7SSiddharth Bhat // preload invariant loads. Note: This should happen before the RTC 34059e3db2b7SSiddharth Bhat // because the RTC may depend on values that are invariant load hoisted. 340671dfb3ebSSiddharth Bhat if (!NodeBuilder.preloadInvariantLoads()) { 340771dfb3ebSSiddharth Bhat DEBUG(dbgs() << "preloading invariant loads failed in function: " + 34084ebeb356SSiddharth Bhat S->getFunction().getName() + 34094ebeb356SSiddharth Bhat " | Scop Region: " + S->getNameStr()); 341071dfb3ebSSiddharth Bhat // adjust the dominator tree accordingly. 341171dfb3ebSSiddharth Bhat auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 341271dfb3ebSSiddharth Bhat assert(ExitingBlock); 341371dfb3ebSSiddharth Bhat auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 341471dfb3ebSSiddharth Bhat assert(MergeBlock); 341571dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*StartBlock, Builder); 341671dfb3ebSSiddharth Bhat polly::markBlockUnreachable(*ExitingBlock, Builder); 341771dfb3ebSSiddharth Bhat auto *ExitingBB = S->getExitingBlock(); 341871dfb3ebSSiddharth Bhat assert(ExitingBB); 34199e3db2b7SSiddharth Bhat 342071dfb3ebSSiddharth Bhat DT->changeImmediateDominator(MergeBlock, ExitingBB); 342171dfb3ebSSiddharth Bhat DT->eraseNode(ExitingBlock); 342271dfb3ebSSiddharth Bhat isl_ast_expr_free(Condition); 342371dfb3ebSSiddharth Bhat isl_ast_node_free(Root); 342471dfb3ebSSiddharth Bhat } else { 342571dfb3ebSSiddharth Bhat 342671dfb3ebSSiddharth Bhat NodeBuilder.addParameters(S->getContext().release()); 3427cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 3428cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3429cb1aef8dSTobias Grosser 343038fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 3431fa7b0802STobias Grosser 343238fc0aedSTobias Grosser NodeBuilder.create(Root); 343371dfb3ebSSiddharth Bhat } 34345857b701STobias Grosser 3435bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 3436bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3437de244eb4STobias Grosser /// point in running it on a GPU. 3438bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 343903346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 3440bc653f20STobias Grosser 34415857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 344203346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 344338fc0aedSTobias Grosser } 344438fc0aedSTobias Grosser 3445e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 3446e938517eSTobias Grosser S = &CurrentScop; 344738fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 344838fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 344938fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 34507b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 345138fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3452e938517eSTobias Grosser 3453f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 3454f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 3455f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 3456bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 3457bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 34588fc6cdfbSTobias Grosser if (containsInvalidKernelFunction(CurrentScop, 34598fc6cdfbSTobias Grosser Architecture == GPUArch::NVPTX64)) { 3460f291c8d5SSiddharth Bhat DEBUG( 3461638316daSSiddharth Bhat dbgs() << getUniqueScopName(S) 3462638316daSSiddharth Bhat << " contains function which cannot be materialised in a GPU " 3463f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3464bccaea57SSiddharth Bhat return false; 3465f291c8d5SSiddharth Bhat } 3466bccaea57SSiddharth Bhat 3467e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3468e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3469f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 347038fc0aedSTobias Grosser 347102ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 347232837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 347302ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 3474638316daSSiddharth Bhat } else { 3475638316daSSiddharth Bhat DEBUG(dbgs() << getUniqueScopName(S) 3476638316daSSiddharth Bhat << " has empty PPCGGen->tree. Bailing out.\n"); 347702ca346eSSingapuram Sanjay Srivallabh } 347838fc0aedSTobias Grosser 3479b307ed4dSTobias Grosser freeOptions(PPCGScop); 3480f384594dSTobias Grosser freePPCGGen(PPCGGen); 3481e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3482e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3483e938517eSTobias Grosser 3484e938517eSTobias Grosser return true; 3485e938517eSTobias Grosser } 34869dfe4e7cSTobias Grosser 34879dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 34889dfe4e7cSTobias Grosser 34899dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 34909dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 34919dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 34929dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 34935cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 34949dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 34959dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 34969dfe4e7cSTobias Grosser 34979dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 34989dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 34999dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 35009dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 35019dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 35025cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 35039dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 35049dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 35059dfe4e7cSTobias Grosser 35069dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 35079dfe4e7cSTobias Grosser // region tree. 35089dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 35099dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 35109dfe4e7cSTobias Grosser } 35119dfe4e7cSTobias Grosser }; 351224222c73STobias Grosser } // namespace 35139dfe4e7cSTobias Grosser 35149dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 35159dfe4e7cSTobias Grosser 351617f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 351717f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 351817f01968SSiddharth Bhat generator->Runtime = Runtime; 351917f01968SSiddharth Bhat generator->Architecture = Arch; 352017f01968SSiddharth Bhat return generator; 352117f01968SSiddharth Bhat } 35229dfe4e7cSTobias Grosser 35239dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 35249dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 35259dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 35269dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 35279dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 35289dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 35299dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 35305cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 35319dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 35329dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3533