19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 29dfe4e7cSTobias Grosser // 39dfe4e7cSTobias Grosser // The LLVM Compiler Infrastructure 49dfe4e7cSTobias Grosser // 59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source 69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details. 79dfe4e7cSTobias Grosser // 89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 99dfe4e7cSTobias Grosser // 109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg 119dfe4e7cSTobias Grosser // GPU mapping strategy. 129dfe4e7cSTobias Grosser // 139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===// 149dfe4e7cSTobias Grosser 1517f01968SSiddharth Bhat #include "polly/CodeGen/PPCGCodeGeneration.h" 16cb1aef8dSTobias Grosser #include "polly/CodeGen/IslAst.h" 179dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h" 1838fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h" 199dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h" 209dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h" 21f384594dSTobias Grosser #include "polly/Options.h" 22629109b6STobias Grosser #include "polly/ScopDetection.h" 239dfe4e7cSTobias Grosser #include "polly/ScopInfo.h" 24edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h" 2574dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h" 269dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h" 279dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h" 289dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h" 299dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h" 3174dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h" 3274dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h" 33e1a98343STobias Grosser #include "llvm/IR/Verifier.h" 3474dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h" 3574dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h" 3674dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h" 379a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h" 38750160e2STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h" 399dfe4e7cSTobias Grosser 40f384594dSTobias Grosser #include "isl/union_map.h" 41f384594dSTobias Grosser 42e938517eSTobias Grosser extern "C" { 43a56f8f8eSTobias Grosser #include "ppcg/cuda.h" 44a56f8f8eSTobias Grosser #include "ppcg/gpu.h" 45a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h" 46a56f8f8eSTobias Grosser #include "ppcg/ppcg.h" 47a56f8f8eSTobias Grosser #include "ppcg/schedule.h" 48e938517eSTobias Grosser } 49e938517eSTobias Grosser 509dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h" 519dfe4e7cSTobias Grosser 529dfe4e7cSTobias Grosser using namespace polly; 539dfe4e7cSTobias Grosser using namespace llvm; 549dfe4e7cSTobias Grosser 559dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg" 569dfe4e7cSTobias Grosser 57f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 58f384594dSTobias Grosser cl::desc("Dump the computed GPU Schedule"), 59681bd568STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 60f384594dSTobias Grosser cl::cat(PollyCategory)); 6169b46751STobias Grosser 6269b46751STobias Grosser static cl::opt<bool> 6369b46751STobias Grosser DumpCode("polly-acc-dump-code", 6469b46751STobias Grosser cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 6569b46751STobias Grosser cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 6669b46751STobias Grosser 6732837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 6832837fe3STobias Grosser cl::desc("Dump the kernel LLVM-IR"), 6932837fe3STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7032837fe3STobias Grosser cl::cat(PollyCategory)); 7132837fe3STobias Grosser 7274dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 7374dc3cb4STobias Grosser cl::desc("Dump the kernel assembly code"), 7474dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 7574dc3cb4STobias Grosser cl::cat(PollyCategory)); 7674dc3cb4STobias Grosser 7774dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath", 7874dc3cb4STobias Grosser cl::desc("Allow unsafe math optimizations"), 7974dc3cb4STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 8074dc3cb4STobias Grosser cl::cat(PollyCategory)); 81b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared", 82b513b491STobias Grosser cl::desc("Use shared memory"), cl::Hidden, 83b513b491STobias Grosser cl::init(false), cl::ZeroOrMore, 84b513b491STobias Grosser cl::cat(PollyCategory)); 85130ca30fSTobias Grosser static cl::opt<bool> PrivateMemory("polly-acc-use-private", 86130ca30fSTobias Grosser cl::desc("Use private memory"), cl::Hidden, 87130ca30fSTobias Grosser cl::init(false), cl::ZeroOrMore, 88130ca30fSTobias Grosser cl::cat(PollyCategory)); 8974dc3cb4STobias Grosser 90abed4969SSiddharth Bhat static cl::opt<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91abed4969SSiddharth Bhat cl::desc("Generate Host kernel code assuming" 92abed4969SSiddharth Bhat " that all memory has been" 93abed4969SSiddharth Bhat " declared as managed memory"), 94abed4969SSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 95abed4969SSiddharth Bhat cl::cat(PollyCategory)); 96abed4969SSiddharth Bhat 9765d7f72fSSiddharth Bhat static cl::opt<bool> 9865d7f72fSSiddharth Bhat FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 9965d7f72fSSiddharth Bhat cl::desc("Fail and generate a backtrace if" 10065d7f72fSSiddharth Bhat " verifyModule fails on the GPU " 10165d7f72fSSiddharth Bhat " kernel module."), 10265d7f72fSSiddharth Bhat cl::Hidden, cl::init(false), cl::ZeroOrMore, 10365d7f72fSSiddharth Bhat cl::cat(PollyCategory)); 10465d7f72fSSiddharth Bhat 10574dc3cb4STobias Grosser static cl::opt<std::string> 10674dc3cb4STobias Grosser CudaVersion("polly-acc-cuda-version", 10774dc3cb4STobias Grosser cl::desc("The CUDA version to compile for"), cl::Hidden, 10874dc3cb4STobias Grosser cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 10974dc3cb4STobias Grosser 11082f2af35STobias Grosser static cl::opt<int> 11182f2af35STobias Grosser MinCompute("polly-acc-mincompute", 11282f2af35STobias Grosser cl::desc("Minimal number of compute statements to run on GPU."), 11382f2af35STobias Grosser cl::Hidden, cl::init(10 * 512 * 512)); 11482f2af35STobias Grosser 115a82f2d26SSiddharth Bhat /// Used to store information PPCG wants for kills. This information is 116a82f2d26SSiddharth Bhat /// used by live range reordering. 117a82f2d26SSiddharth Bhat /// 118a82f2d26SSiddharth Bhat /// @see computeLiveRangeReordering 119a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGScop 120a82f2d26SSiddharth Bhat /// @see GPUNodeBuilder::createPPCGProg 121a82f2d26SSiddharth Bhat struct MustKillsInfo { 122a82f2d26SSiddharth Bhat /// Collection of all kill statements that will be sequenced at the end of 123a82f2d26SSiddharth Bhat /// PPCGScop->schedule. 124a82f2d26SSiddharth Bhat /// 125a82f2d26SSiddharth Bhat /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126a82f2d26SSiddharth Bhat /// which merges schedules in *arbitrary* order. 127a82f2d26SSiddharth Bhat /// (we don't care about the order of the kills anyway). 128a82f2d26SSiddharth Bhat isl::schedule KillsSchedule; 129a82f2d26SSiddharth Bhat /// Map from kill statement instances to scalars that need to be 130a82f2d26SSiddharth Bhat /// killed. 131a82f2d26SSiddharth Bhat /// 132edfef5aeSSiddharth Bhat /// We currently derive kill information for: 133edfef5aeSSiddharth Bhat /// 1. phi nodes. PHI nodes are not alive outside the scop and can 134edfef5aeSSiddharth Bhat /// consequently all be killed. 135edfef5aeSSiddharth Bhat /// 2. Scalar arrays that are not used outside the Scop. This is 136edfef5aeSSiddharth Bhat /// checked by `isScalarUsesContainedInScop`. 137edfef5aeSSiddharth Bhat /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 138a82f2d26SSiddharth Bhat isl::union_map TaggedMustKills; 139a82f2d26SSiddharth Bhat 1409e3db2b7SSiddharth Bhat /// Tagged must kills stripped of the tags. 1419e3db2b7SSiddharth Bhat /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 1429e3db2b7SSiddharth Bhat isl::union_map MustKills; 1439e3db2b7SSiddharth Bhat 1449e3db2b7SSiddharth Bhat MustKillsInfo() : KillsSchedule(nullptr) {} 145a82f2d26SSiddharth Bhat }; 146a82f2d26SSiddharth Bhat 147761e5b93SSiddharth Bhat /// Check if SAI's uses are entirely contained within Scop S. 148761e5b93SSiddharth Bhat /// If a scalar is used only with a Scop, we are free to kill it, as no data 149761e5b93SSiddharth Bhat /// can flow in/out of the value any more. 150761e5b93SSiddharth Bhat /// @see computeMustKillsInfo 151761e5b93SSiddharth Bhat static bool isScalarUsesContainedInScop(const Scop &S, 152761e5b93SSiddharth Bhat const ScopArrayInfo *SAI) { 153761e5b93SSiddharth Bhat assert(SAI->isValueKind() && "this function only deals with scalars." 154761e5b93SSiddharth Bhat " Dealing with arrays required alias analysis"); 155761e5b93SSiddharth Bhat 156761e5b93SSiddharth Bhat const Region &R = S.getRegion(); 157761e5b93SSiddharth Bhat for (User *U : SAI->getBasePtr()->users()) { 158761e5b93SSiddharth Bhat Instruction *I = dyn_cast<Instruction>(U); 159761e5b93SSiddharth Bhat assert(I && "invalid user of scop array info"); 160761e5b93SSiddharth Bhat if (!R.contains(I)) 161761e5b93SSiddharth Bhat return false; 162761e5b93SSiddharth Bhat } 163761e5b93SSiddharth Bhat return true; 164761e5b93SSiddharth Bhat } 165761e5b93SSiddharth Bhat 166a82f2d26SSiddharth Bhat /// Compute must-kills needed to enable live range reordering with PPCG. 167a82f2d26SSiddharth Bhat /// 168a82f2d26SSiddharth Bhat /// @params S The Scop to compute live range reordering information 169a82f2d26SSiddharth Bhat /// @returns live range reordering information that can be used to setup 170a82f2d26SSiddharth Bhat /// PPCG. 171a82f2d26SSiddharth Bhat static MustKillsInfo computeMustKillsInfo(const Scop &S) { 172a82f2d26SSiddharth Bhat const isl::space ParamSpace(isl::manage(S.getParamSpace())); 173a82f2d26SSiddharth Bhat MustKillsInfo Info; 174a82f2d26SSiddharth Bhat 175761e5b93SSiddharth Bhat // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 176761e5b93SSiddharth Bhat // 1.1 phi nodes in scop. 177761e5b93SSiddharth Bhat // 1.2 scalars that are only used within the scop 178a82f2d26SSiddharth Bhat SmallVector<isl::id, 4> KillMemIds; 179a82f2d26SSiddharth Bhat for (ScopArrayInfo *SAI : S.arrays()) { 180761e5b93SSiddharth Bhat if (SAI->isPHIKind() || 181761e5b93SSiddharth Bhat (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 182*77eef90fSTobias Grosser KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 183a82f2d26SSiddharth Bhat } 184a82f2d26SSiddharth Bhat 185a82f2d26SSiddharth Bhat Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 1869e3db2b7SSiddharth Bhat Info.MustKills = isl::union_map::empty(isl::space(ParamSpace)); 187a82f2d26SSiddharth Bhat 188a82f2d26SSiddharth Bhat // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 189a82f2d26SSiddharth Bhat // schedule: 190a82f2d26SSiddharth Bhat // - filter: "[control] -> { }" 191a82f2d26SSiddharth Bhat // So, we choose to not create this to keep the output a little nicer, 192a82f2d26SSiddharth Bhat // at the cost of some code complexity. 193a82f2d26SSiddharth Bhat Info.KillsSchedule = nullptr; 194a82f2d26SSiddharth Bhat 195edfef5aeSSiddharth Bhat for (isl::id &ToKillId : KillMemIds) { 196a82f2d26SSiddharth Bhat isl::id KillStmtId = isl::id::alloc( 197edfef5aeSSiddharth Bhat S.getIslCtx(), 198edfef5aeSSiddharth Bhat std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 199a82f2d26SSiddharth Bhat 200a82f2d26SSiddharth Bhat // NOTE: construction of tagged_must_kill: 201a82f2d26SSiddharth Bhat // 2. We need to construct a map: 202edfef5aeSSiddharth Bhat // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 203a82f2d26SSiddharth Bhat // To construct this, we use `isl_map_domain_product` on 2 maps`: 204edfef5aeSSiddharth Bhat // 2a. StmtToScalar: 205edfef5aeSSiddharth Bhat // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 206edfef5aeSSiddharth Bhat // 2b. PhantomRefToScalar: 207edfef5aeSSiddharth Bhat // [param] -> { ref_phantom[] -> scalar_to_kill[] } 208a82f2d26SSiddharth Bhat // 209a82f2d26SSiddharth Bhat // Combining these with `isl_map_domain_product` gives us 210a82f2d26SSiddharth Bhat // TaggedMustKill: 211edfef5aeSSiddharth Bhat // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 212a82f2d26SSiddharth Bhat 213edfef5aeSSiddharth Bhat // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 214edfef5aeSSiddharth Bhat isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace)); 215edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 216edfef5aeSSiddharth Bhat StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 217a82f2d26SSiddharth Bhat 218a82f2d26SSiddharth Bhat isl::id PhantomRefId = isl::id::alloc( 219edfef5aeSSiddharth Bhat S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 220edfef5aeSSiddharth Bhat nullptr); 221a82f2d26SSiddharth Bhat 222edfef5aeSSiddharth Bhat // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 223edfef5aeSSiddharth Bhat isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace)); 224edfef5aeSSiddharth Bhat PhantomRefToScalar = 225edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 226edfef5aeSSiddharth Bhat PhantomRefToScalar = 227edfef5aeSSiddharth Bhat PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 228a82f2d26SSiddharth Bhat 229edfef5aeSSiddharth Bhat // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 230edfef5aeSSiddharth Bhat isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 231a82f2d26SSiddharth Bhat Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 232a82f2d26SSiddharth Bhat 2339e3db2b7SSiddharth Bhat // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 2349e3db2b7SSiddharth Bhat Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 2359e3db2b7SSiddharth Bhat 236a82f2d26SSiddharth Bhat // 3. Create the kill schedule of the form: 237a82f2d26SSiddharth Bhat // "[param] -> { Stmt_phantom[] }" 238a82f2d26SSiddharth Bhat // Then add this to Info.KillsSchedule. 239a82f2d26SSiddharth Bhat isl::space KillStmtSpace = ParamSpace; 240a82f2d26SSiddharth Bhat KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 241a82f2d26SSiddharth Bhat isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 242a82f2d26SSiddharth Bhat 243a82f2d26SSiddharth Bhat isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 244a82f2d26SSiddharth Bhat if (Info.KillsSchedule) 245a82f2d26SSiddharth Bhat Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 246a82f2d26SSiddharth Bhat else 247a82f2d26SSiddharth Bhat Info.KillsSchedule = KillSchedule; 248a82f2d26SSiddharth Bhat } 249a82f2d26SSiddharth Bhat 250a82f2d26SSiddharth Bhat return Info; 251a82f2d26SSiddharth Bhat } 252a82f2d26SSiddharth Bhat 25360c60025STobias Grosser /// Create the ast expressions for a ScopStmt. 25460c60025STobias Grosser /// 25560c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each 25660c60025STobias Grosser /// of the scheduled ScopStmts. 25760c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 258edb885cbSTobias Grosser void *StmtT, isl_ast_build *Build, 25960c60025STobias Grosser isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 26060c60025STobias Grosser isl_id *Id, void *User), 26160c60025STobias Grosser void *UserIndex, 26260c60025STobias Grosser isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 263edb885cbSTobias Grosser void *UserExpr) { 26460c60025STobias Grosser 265edb885cbSTobias Grosser ScopStmt *Stmt = (ScopStmt *)StmtT; 26660c60025STobias Grosser 267edb885cbSTobias Grosser isl_ctx *Ctx; 268edb885cbSTobias Grosser 269edb885cbSTobias Grosser if (!Stmt || !Build) 270edb885cbSTobias Grosser return NULL; 271edb885cbSTobias Grosser 272edb885cbSTobias Grosser Ctx = isl_ast_build_get_ctx(Build); 273edb885cbSTobias Grosser isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 274edb885cbSTobias Grosser 275edb885cbSTobias Grosser for (MemoryAccess *Acc : *Stmt) { 276edb885cbSTobias Grosser isl_map *AddrFunc = Acc->getAddressFunction(); 277edb885cbSTobias Grosser AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 278edb885cbSTobias Grosser isl_id *RefId = Acc->getId(); 279edb885cbSTobias Grosser isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 280edb885cbSTobias Grosser isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 281edb885cbSTobias Grosser MPA = isl_multi_pw_aff_coalesce(MPA); 282edb885cbSTobias Grosser MPA = FunctionIndex(MPA, RefId, UserIndex); 283edb885cbSTobias Grosser isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 284edb885cbSTobias Grosser Access = FunctionExpr(Access, RefId, UserExpr); 285edb885cbSTobias Grosser RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 286edb885cbSTobias Grosser } 287edb885cbSTobias Grosser 288edb885cbSTobias Grosser return RefToExpr; 28960c60025STobias Grosser } 290f384594dSTobias Grosser 291a90be207SSiddharth Bhat /// Given a LLVM Type, compute its size in bytes, 292a90be207SSiddharth Bhat static int computeSizeInBytes(const Type *T) { 293a90be207SSiddharth Bhat int bytes = T->getPrimitiveSizeInBits() / 8; 294a90be207SSiddharth Bhat if (bytes == 0) 295a90be207SSiddharth Bhat bytes = T->getScalarSizeInBits() / 8; 296a90be207SSiddharth Bhat return bytes; 297a90be207SSiddharth Bhat } 298a90be207SSiddharth Bhat 29938fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST. 30038fc0aedSTobias Grosser /// 30138fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 302a6d48f59SMichael Kruse /// generates code for general-purpose AST nodes, with special functionality 30338fc0aedSTobias Grosser /// for generating GPU specific user nodes. 30438fc0aedSTobias Grosser /// 30538fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser 30638fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder { 30738fc0aedSTobias Grosser public: 3082d950f36SPhilip Pfaffe GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 30938fc0aedSTobias Grosser const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 310acf80064SEli Friedman DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 31117f01968SSiddharth Bhat gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 3122d950f36SPhilip Pfaffe : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 31317f01968SSiddharth Bhat Prog(Prog), Runtime(Runtime), Arch(Arch) { 314edb885cbSTobias Grosser getExprBuilder().setIDToSAI(&IDToSAI); 315edb885cbSTobias Grosser } 31638fc0aedSTobias Grosser 317fa7b0802STobias Grosser /// Create after-run-time-check initialization code. 318fa7b0802STobias Grosser void initializeAfterRTH(); 319fa7b0802STobias Grosser 320fa7b0802STobias Grosser /// Finalize the generated scop. 321fa7b0802STobias Grosser virtual void finalize(); 322fa7b0802STobias Grosser 3235857b701STobias Grosser /// Track if the full build process was successful. 3245857b701STobias Grosser /// 3255857b701STobias Grosser /// This value is set to false, if throughout the build process an error 3265857b701STobias Grosser /// occurred which prevents us from generating valid GPU code. 3275857b701STobias Grosser bool BuildSuccessful = true; 3285857b701STobias Grosser 329bc653f20STobias Grosser /// The maximal number of loops surrounding a sequential kernel. 330bc653f20STobias Grosser unsigned DeepestSequential = 0; 331bc653f20STobias Grosser 332bc653f20STobias Grosser /// The maximal number of loops surrounding a parallel kernel. 333bc653f20STobias Grosser unsigned DeepestParallel = 0; 334bc653f20STobias Grosser 33579f13b9aSSingapuram Sanjay Srivallabh /// Return the name to set for the ptx_kernel. 33679f13b9aSSingapuram Sanjay Srivallabh std::string getKernelFuncName(int Kernel_id); 33779f13b9aSSingapuram Sanjay Srivallabh 33838fc0aedSTobias Grosser private: 33974dc3cb4STobias Grosser /// A vector of array base pointers for which a new ScopArrayInfo was created. 34074dc3cb4STobias Grosser /// 34174dc3cb4STobias Grosser /// This vector is used to delete the ScopArrayInfo when it is not needed any 34274dc3cb4STobias Grosser /// more. 34374dc3cb4STobias Grosser std::vector<Value *> LocalArrays; 34474dc3cb4STobias Grosser 34513c78e4dSTobias Grosser /// A map from ScopArrays to their corresponding device allocations. 34613c78e4dSTobias Grosser std::map<ScopArrayInfo *, Value *> DeviceAllocations; 3477287aeddSTobias Grosser 348fa7b0802STobias Grosser /// The current GPU context. 349fa7b0802STobias Grosser Value *GPUContext; 350fa7b0802STobias Grosser 351b513b491STobias Grosser /// The set of isl_ids allocated in the kernel 352b513b491STobias Grosser std::vector<isl_id *> KernelIds; 353b513b491STobias Grosser 35432837fe3STobias Grosser /// A module containing GPU code. 35532837fe3STobias Grosser /// 35632837fe3STobias Grosser /// This pointer is only set in case we are currently generating GPU code. 35732837fe3STobias Grosser std::unique_ptr<Module> GPUModule; 35832837fe3STobias Grosser 35932837fe3STobias Grosser /// The GPU program we generate code for. 36032837fe3STobias Grosser gpu_prog *Prog; 36132837fe3STobias Grosser 36217f01968SSiddharth Bhat /// The GPU Runtime implementation to use (OpenCL or CUDA). 36317f01968SSiddharth Bhat GPURuntime Runtime; 36417f01968SSiddharth Bhat 36517f01968SSiddharth Bhat /// The GPU Architecture to target. 36617f01968SSiddharth Bhat GPUArch Arch; 36717f01968SSiddharth Bhat 368472f9654STobias Grosser /// Class to free isl_ids. 369472f9654STobias Grosser class IslIdDeleter { 370472f9654STobias Grosser public: 371472f9654STobias Grosser void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 372472f9654STobias Grosser }; 373472f9654STobias Grosser 374472f9654STobias Grosser /// A set containing all isl_ids allocated in a GPU kernel. 375472f9654STobias Grosser /// 376472f9654STobias Grosser /// By releasing this set all isl_ids will be freed. 377472f9654STobias Grosser std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 378472f9654STobias Grosser 379edb885cbSTobias Grosser IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 380edb885cbSTobias Grosser 38138fc0aedSTobias Grosser /// Create code for user-defined AST nodes. 38238fc0aedSTobias Grosser /// 38338fc0aedSTobias Grosser /// These AST nodes can be of type: 38438fc0aedSTobias Grosser /// 38538fc0aedSTobias Grosser /// - ScopStmt: A computational statement (TODO) 38638fc0aedSTobias Grosser /// - Kernel: A GPU kernel call (TODO) 38713c78e4dSTobias Grosser /// - Data-Transfer: A GPU <-> CPU data-transfer 3885260c041STobias Grosser /// - In-kernel synchronization 3895260c041STobias Grosser /// - In-kernel memory copy statement 39038fc0aedSTobias Grosser /// 3911fb9b64dSTobias Grosser /// @param UserStmt The ast node to generate code for. 3921fb9b64dSTobias Grosser virtual void createUser(__isl_take isl_ast_node *UserStmt); 39332837fe3STobias Grosser 39413c78e4dSTobias Grosser enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 39513c78e4dSTobias Grosser 39613c78e4dSTobias Grosser /// Create code for a data transfer statement 39713c78e4dSTobias Grosser /// 39813c78e4dSTobias Grosser /// @param TransferStmt The data transfer statement. 39913c78e4dSTobias Grosser /// @param Direction The direction in which to transfer data. 40013c78e4dSTobias Grosser void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 40113c78e4dSTobias Grosser enum DataDirection Direction); 40213c78e4dSTobias Grosser 403edb885cbSTobias Grosser /// Find llvm::Values referenced in GPU kernel. 404edb885cbSTobias Grosser /// 405edb885cbSTobias Grosser /// @param Kernel The kernel to scan for llvm::Values 406edb885cbSTobias Grosser /// 407f291c8d5SSiddharth Bhat /// @returns A pair, whose first element contains the set of values 408f291c8d5SSiddharth Bhat /// referenced by the kernel, and whose second element contains the 409f291c8d5SSiddharth Bhat /// set of functions referenced by the kernel. All functions in the 410f291c8d5SSiddharth Bhat /// second set satisfy isValidFunctionInKernel. 411f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 412f291c8d5SSiddharth Bhat getReferencesInKernel(ppcg_kernel *Kernel); 413edb885cbSTobias Grosser 41479a947c2STobias Grosser /// Compute the sizes of the execution grid for a given kernel. 41579a947c2STobias Grosser /// 41679a947c2STobias Grosser /// @param Kernel The kernel to compute grid sizes for. 41779a947c2STobias Grosser /// 41879a947c2STobias Grosser /// @returns A tuple with grid sizes for X and Y dimension 41979a947c2STobias Grosser std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 42079a947c2STobias Grosser 421abed4969SSiddharth Bhat /// Creates a array that can be sent to the kernel on the device using a 422abed4969SSiddharth Bhat /// host pointer. This is required for managed memory, when we directly send 423abed4969SSiddharth Bhat /// host pointers to the device. 424abed4969SSiddharth Bhat /// \note 425abed4969SSiddharth Bhat /// This is to be used only with managed memory 426abed4969SSiddharth Bhat Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 427abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo); 428abed4969SSiddharth Bhat 42979a947c2STobias Grosser /// Compute the sizes of the thread blocks for a given kernel. 43079a947c2STobias Grosser /// 43179a947c2STobias Grosser /// @param Kernel The kernel to compute thread block sizes for. 43279a947c2STobias Grosser /// 43379a947c2STobias Grosser /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 43479a947c2STobias Grosser std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 43579a947c2STobias Grosser 436a90be207SSiddharth Bhat /// Store a specific kernel launch parameter in the array of kernel launch 437a90be207SSiddharth Bhat /// parameters. 438a90be207SSiddharth Bhat /// 439a90be207SSiddharth Bhat /// @param Parameters The list of parameters in which to store. 440a90be207SSiddharth Bhat /// @param Param The kernel launch parameter to store. 441a90be207SSiddharth Bhat /// @param Index The index in the parameter list, at which to store the 442a90be207SSiddharth Bhat /// parameter. 443a90be207SSiddharth Bhat void insertStoreParameter(Instruction *Parameters, Instruction *Param, 444a90be207SSiddharth Bhat int Index); 445a90be207SSiddharth Bhat 44679a947c2STobias Grosser /// Create kernel launch parameters. 44779a947c2STobias Grosser /// 44879a947c2STobias Grosser /// @param Kernel The kernel to create parameters for. 44979a947c2STobias Grosser /// @param F The kernel function that has been created. 45057693272STobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 45179a947c2STobias Grosser /// 45279a947c2STobias Grosser /// @returns A stack allocated array with pointers to the parameter 45379a947c2STobias Grosser /// values that are passed to the kernel. 45457693272STobias Grosser Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 45557693272STobias Grosser SetVector<Value *> SubtreeValues); 45679a947c2STobias Grosser 457b513b491STobias Grosser /// Create declarations for kernel variable. 458b513b491STobias Grosser /// 459b513b491STobias Grosser /// This includes shared memory declarations. 460b513b491STobias Grosser /// 461b513b491STobias Grosser /// @param Kernel The kernel definition to create variables for. 462b513b491STobias Grosser /// @param FN The function into which to generate the variables. 463b513b491STobias Grosser void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 464b513b491STobias Grosser 465c1c6a2a6STobias Grosser /// Add CUDA annotations to module. 466c1c6a2a6STobias Grosser /// 467c1c6a2a6STobias Grosser /// Add a set of CUDA annotations that declares the maximal block dimensions 468c1c6a2a6STobias Grosser /// that will be used to execute the CUDA kernel. This allows the NVIDIA 469c1c6a2a6STobias Grosser /// PTX compiler to bound the number of allocated registers to ensure the 470c1c6a2a6STobias Grosser /// resulting kernel is known to run with up to as many block dimensions 471c1c6a2a6STobias Grosser /// as specified here. 472c1c6a2a6STobias Grosser /// 473c1c6a2a6STobias Grosser /// @param M The module to add the annotations to. 474c1c6a2a6STobias Grosser /// @param BlockDimX The size of block dimension X. 475c1c6a2a6STobias Grosser /// @param BlockDimY The size of block dimension Y. 476c1c6a2a6STobias Grosser /// @param BlockDimZ The size of block dimension Z. 477c1c6a2a6STobias Grosser void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 478c1c6a2a6STobias Grosser Value *BlockDimZ); 479c1c6a2a6STobias Grosser 48032837fe3STobias Grosser /// Create GPU kernel. 48132837fe3STobias Grosser /// 48232837fe3STobias Grosser /// Code generate the kernel described by @p KernelStmt. 48332837fe3STobias Grosser /// 48432837fe3STobias Grosser /// @param KernelStmt The ast node to generate kernel code for. 48532837fe3STobias Grosser void createKernel(__isl_take isl_ast_node *KernelStmt); 48632837fe3STobias Grosser 48713c78e4dSTobias Grosser /// Generate code that computes the size of an array. 48813c78e4dSTobias Grosser /// 48913c78e4dSTobias Grosser /// @param Array The array for which to compute a size. 49013c78e4dSTobias Grosser Value *getArraySize(gpu_array_info *Array); 49113c78e4dSTobias Grosser 492aaabbbf8STobias Grosser /// Generate code to compute the minimal offset at which an array is accessed. 493aaabbbf8STobias Grosser /// 494aaabbbf8STobias Grosser /// The offset of an array is the minimal array location accessed in a scop. 495aaabbbf8STobias Grosser /// 496aaabbbf8STobias Grosser /// Example: 497aaabbbf8STobias Grosser /// 498aaabbbf8STobias Grosser /// for (long i = 0; i < 100; i++) 499aaabbbf8STobias Grosser /// A[i + 42] += ... 500aaabbbf8STobias Grosser /// 501aaabbbf8STobias Grosser /// getArrayOffset(A) results in 42. 502aaabbbf8STobias Grosser /// 503aaabbbf8STobias Grosser /// @param Array The array for which to compute the offset. 504aaabbbf8STobias Grosser /// @returns An llvm::Value that contains the offset of the array. 505aaabbbf8STobias Grosser Value *getArrayOffset(gpu_array_info *Array); 506aaabbbf8STobias Grosser 50700bb5a99STobias Grosser /// Prepare the kernel arguments for kernel code generation 50800bb5a99STobias Grosser /// 50900bb5a99STobias Grosser /// @param Kernel The kernel to generate code for. 51000bb5a99STobias Grosser /// @param FN The function created for the kernel. 51100bb5a99STobias Grosser void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 51200bb5a99STobias Grosser 51332837fe3STobias Grosser /// Create kernel function. 51432837fe3STobias Grosser /// 51532837fe3STobias Grosser /// Create a kernel function located in a newly created module that can serve 51632837fe3STobias Grosser /// as target for device code generation. Set the Builder to point to the 51732837fe3STobias Grosser /// start block of this newly created function. 51832837fe3STobias Grosser /// 51932837fe3STobias Grosser /// @param Kernel The kernel to generate code for. 520edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 521f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by this 522f291c8d5SSiddharth Bhat /// kernel. 523edb885cbSTobias Grosser void createKernelFunction(ppcg_kernel *Kernel, 524f291c8d5SSiddharth Bhat SetVector<Value *> &SubtreeValues, 525f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions); 52632837fe3STobias Grosser 52732837fe3STobias Grosser /// Create the declaration of a kernel function. 52832837fe3STobias Grosser /// 52932837fe3STobias Grosser /// The kernel function takes as arguments: 53032837fe3STobias Grosser /// 53132837fe3STobias Grosser /// - One i8 pointer for each external array reference used in the kernel. 532f6044bd0STobias Grosser /// - Host iterators 533c84a1995STobias Grosser /// - Parameters 53432837fe3STobias Grosser /// - Other LLVM Value references (TODO) 53532837fe3STobias Grosser /// 53632837fe3STobias Grosser /// @param Kernel The kernel to generate the function declaration for. 537edb885cbSTobias Grosser /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 538edb885cbSTobias Grosser /// 53932837fe3STobias Grosser /// @returns The newly declared function. 540edb885cbSTobias Grosser Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 541edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues); 54232837fe3STobias Grosser 543472f9654STobias Grosser /// Insert intrinsic functions to obtain thread and block ids. 544472f9654STobias Grosser /// 545472f9654STobias Grosser /// @param The kernel to generate the intrinsic functions for. 546472f9654STobias Grosser void insertKernelIntrinsics(ppcg_kernel *Kernel); 547472f9654STobias Grosser 5482f3073b5SPhilipp Schaad /// Insert function calls to retrieve the SPIR group/local ids. 5492f3073b5SPhilipp Schaad /// 5502f3073b5SPhilipp Schaad /// @param The kernel to generate the function calls for. 5512f3073b5SPhilipp Schaad void insertKernelCallsSPIR(ppcg_kernel *Kernel); 5522f3073b5SPhilipp Schaad 553f291c8d5SSiddharth Bhat /// Setup the creation of functions referenced by the GPU kernel. 554f291c8d5SSiddharth Bhat /// 555f291c8d5SSiddharth Bhat /// 1. Create new function declarations in GPUModule which are the same as 556f291c8d5SSiddharth Bhat /// SubtreeFunctions. 557f291c8d5SSiddharth Bhat /// 558f291c8d5SSiddharth Bhat /// 2. Populate IslNodeBuilder::ValueMap with mappings from 559f291c8d5SSiddharth Bhat /// old functions (that come from the original module) to new functions 560f291c8d5SSiddharth Bhat /// (that are created within GPUModule). That way, we generate references 561f291c8d5SSiddharth Bhat /// to the correct function (in GPUModule) in BlockGenerator. 562f291c8d5SSiddharth Bhat /// 563f291c8d5SSiddharth Bhat /// @see IslNodeBuilder::ValueMap 564f291c8d5SSiddharth Bhat /// @see BlockGenerator::GlobalMap 565f291c8d5SSiddharth Bhat /// @see BlockGenerator::getNewValue 566f291c8d5SSiddharth Bhat /// @see GPUNodeBuilder::getReferencesInKernel. 567f291c8d5SSiddharth Bhat /// 568f291c8d5SSiddharth Bhat /// @param SubtreeFunctions The set of llvm::Functions referenced by 569f291c8d5SSiddharth Bhat /// this kernel. 570f291c8d5SSiddharth Bhat void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 571f291c8d5SSiddharth Bhat 572b513b491STobias Grosser /// Create a global-to-shared or shared-to-global copy statement. 573b513b491STobias Grosser /// 574b513b491STobias Grosser /// @param CopyStmt The copy statement to generate code for 575b513b491STobias Grosser void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 576b513b491STobias Grosser 577edb885cbSTobias Grosser /// Create code for a ScopStmt called in @p Expr. 578edb885cbSTobias Grosser /// 579edb885cbSTobias Grosser /// @param Expr The expression containing the call. 580edb885cbSTobias Grosser /// @param KernelStmt The kernel statement referenced in the call. 581edb885cbSTobias Grosser void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 582edb885cbSTobias Grosser 5835260c041STobias Grosser /// Create an in-kernel synchronization call. 5845260c041STobias Grosser void createKernelSync(); 5855260c041STobias Grosser 58674dc3cb4STobias Grosser /// Create a PTX assembly string for the current GPU kernel. 58774dc3cb4STobias Grosser /// 58874dc3cb4STobias Grosser /// @returns A string containing the corresponding PTX assembly code. 58974dc3cb4STobias Grosser std::string createKernelASM(); 59074dc3cb4STobias Grosser 59174dc3cb4STobias Grosser /// Remove references from the dominator tree to the kernel function @p F. 59274dc3cb4STobias Grosser /// 59374dc3cb4STobias Grosser /// @param F The function to remove references to. 59474dc3cb4STobias Grosser void clearDominators(Function *F); 59574dc3cb4STobias Grosser 59674dc3cb4STobias Grosser /// Remove references from scalar evolution to the kernel function @p F. 59774dc3cb4STobias Grosser /// 59874dc3cb4STobias Grosser /// @param F The function to remove references to. 59974dc3cb4STobias Grosser void clearScalarEvolution(Function *F); 60074dc3cb4STobias Grosser 60174dc3cb4STobias Grosser /// Remove references from loop info to the kernel function @p F. 60274dc3cb4STobias Grosser /// 60374dc3cb4STobias Grosser /// @param F The function to remove references to. 60474dc3cb4STobias Grosser void clearLoops(Function *F); 60574dc3cb4STobias Grosser 60632837fe3STobias Grosser /// Finalize the generation of the kernel function. 60732837fe3STobias Grosser /// 60832837fe3STobias Grosser /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 60932837fe3STobias Grosser /// dump its IR to stderr. 61057793596STobias Grosser /// 61157793596STobias Grosser /// @returns The Assembly string of the kernel. 61257793596STobias Grosser std::string finalizeKernelFunction(); 613fa7b0802STobias Grosser 61451dfc275STobias Grosser /// Finalize the generation of the kernel arguments. 61551dfc275STobias Grosser /// 61651dfc275STobias Grosser /// This function ensures that not-read-only scalars used in a kernel are 617a6d48f59SMichael Kruse /// stored back to the global memory location they are backed with before 61851dfc275STobias Grosser /// the kernel terminates. 61951dfc275STobias Grosser /// 62051dfc275STobias Grosser /// @params Kernel The kernel to finalize kernel arguments for. 62151dfc275STobias Grosser void finalizeKernelArguments(ppcg_kernel *Kernel); 62251dfc275STobias Grosser 6237287aeddSTobias Grosser /// Create code that allocates memory to store arrays on device. 624fa7b0802STobias Grosser void allocateDeviceArrays(); 625fa7b0802STobias Grosser 6267287aeddSTobias Grosser /// Free all allocated device arrays. 6277287aeddSTobias Grosser void freeDeviceArrays(); 6287287aeddSTobias Grosser 629fa7b0802STobias Grosser /// Create a call to initialize the GPU context. 630fa7b0802STobias Grosser /// 631fa7b0802STobias Grosser /// @returns A pointer to the newly initialized context. 632fa7b0802STobias Grosser Value *createCallInitContext(); 633fa7b0802STobias Grosser 63479a947c2STobias Grosser /// Create a call to get the device pointer for a kernel allocation. 63579a947c2STobias Grosser /// 63679a947c2STobias Grosser /// @param Allocation The Polly GPU allocation 63779a947c2STobias Grosser /// 63879a947c2STobias Grosser /// @returns The device parameter corresponding to this allocation. 63979a947c2STobias Grosser Value *createCallGetDevicePtr(Value *Allocation); 64079a947c2STobias Grosser 641fa7b0802STobias Grosser /// Create a call to free the GPU context. 642fa7b0802STobias Grosser /// 643fa7b0802STobias Grosser /// @param Context A pointer to an initialized GPU context. 644fa7b0802STobias Grosser void createCallFreeContext(Value *Context); 645fa7b0802STobias Grosser 6467287aeddSTobias Grosser /// Create a call to allocate memory on the device. 6477287aeddSTobias Grosser /// 6487287aeddSTobias Grosser /// @param Size The size of memory to allocate 6497287aeddSTobias Grosser /// 6507287aeddSTobias Grosser /// @returns A pointer that identifies this allocation. 651fa7b0802STobias Grosser Value *createCallAllocateMemoryForDevice(Value *Size); 6527287aeddSTobias Grosser 6537287aeddSTobias Grosser /// Create a call to free a device array. 6547287aeddSTobias Grosser /// 6557287aeddSTobias Grosser /// @param Array The device array to free. 6567287aeddSTobias Grosser void createCallFreeDeviceMemory(Value *Array); 65713c78e4dSTobias Grosser 65813c78e4dSTobias Grosser /// Create a call to copy data from host to device. 65913c78e4dSTobias Grosser /// 66013c78e4dSTobias Grosser /// @param HostPtr A pointer to the host data that should be copied. 66113c78e4dSTobias Grosser /// @param DevicePtr A device pointer specifying the location to copy to. 66213c78e4dSTobias Grosser void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 66313c78e4dSTobias Grosser Value *Size); 66413c78e4dSTobias Grosser 66513c78e4dSTobias Grosser /// Create a call to copy data from device to host. 66613c78e4dSTobias Grosser /// 66713c78e4dSTobias Grosser /// @param DevicePtr A pointer to the device data that should be copied. 66813c78e4dSTobias Grosser /// @param HostPtr A host pointer specifying the location to copy to. 66913c78e4dSTobias Grosser void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 67013c78e4dSTobias Grosser Value *Size); 67157793596STobias Grosser 672abed4969SSiddharth Bhat /// Create a call to synchronize Host & Device. 673abed4969SSiddharth Bhat /// \note 674abed4969SSiddharth Bhat /// This is to be used only with managed memory. 675abed4969SSiddharth Bhat void createCallSynchronizeDevice(); 676abed4969SSiddharth Bhat 67757793596STobias Grosser /// Create a call to get a kernel from an assembly string. 67857793596STobias Grosser /// 67957793596STobias Grosser /// @param Buffer The string describing the kernel. 68057793596STobias Grosser /// @param Entry The name of the kernel function to call. 68157793596STobias Grosser /// 68257793596STobias Grosser /// @returns A pointer to a kernel object 68357793596STobias Grosser Value *createCallGetKernel(Value *Buffer, Value *Entry); 68457793596STobias Grosser 68557793596STobias Grosser /// Create a call to free a GPU kernel. 68657793596STobias Grosser /// 68757793596STobias Grosser /// @param GPUKernel THe kernel to free. 68857793596STobias Grosser void createCallFreeKernel(Value *GPUKernel); 68979a947c2STobias Grosser 69079a947c2STobias Grosser /// Create a call to launch a GPU kernel. 69179a947c2STobias Grosser /// 69279a947c2STobias Grosser /// @param GPUKernel The kernel to launch. 69379a947c2STobias Grosser /// @param GridDimX The size of the first grid dimension. 69479a947c2STobias Grosser /// @param GridDimY The size of the second grid dimension. 69579a947c2STobias Grosser /// @param GridBlockX The size of the first block dimension. 69679a947c2STobias Grosser /// @param GridBlockY The size of the second block dimension. 69779a947c2STobias Grosser /// @param GridBlockZ The size of the third block dimension. 698a6d48f59SMichael Kruse /// @param Parameters A pointer to an array that contains itself pointers to 69979a947c2STobias Grosser /// the parameter values passed for each kernel argument. 70079a947c2STobias Grosser void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 70179a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 70279a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 70379a947c2STobias Grosser Value *Parameters); 7041fb9b64dSTobias Grosser }; 7051fb9b64dSTobias Grosser 70679f13b9aSSingapuram Sanjay Srivallabh std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 7071abd9ffaSSingapuram Sanjay Srivallabh return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 7081abd9ffaSSingapuram Sanjay Srivallabh std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 70979f13b9aSSingapuram Sanjay Srivallabh } 71079f13b9aSSingapuram Sanjay Srivallabh 711fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() { 712750160e2STobias Grosser BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 713750160e2STobias Grosser &*Builder.GetInsertPoint(), &DT, &LI); 714750160e2STobias Grosser NewBB->setName("polly.acc.initialize"); 715750160e2STobias Grosser Builder.SetInsertPoint(&NewBB->front()); 716750160e2STobias Grosser 717fa7b0802STobias Grosser GPUContext = createCallInitContext(); 718abed4969SSiddharth Bhat 719abed4969SSiddharth Bhat if (!ManagedMemory) 720fa7b0802STobias Grosser allocateDeviceArrays(); 721fa7b0802STobias Grosser } 722fa7b0802STobias Grosser 723fa7b0802STobias Grosser void GPUNodeBuilder::finalize() { 724abed4969SSiddharth Bhat if (!ManagedMemory) 7257287aeddSTobias Grosser freeDeviceArrays(); 726abed4969SSiddharth Bhat 727fa7b0802STobias Grosser createCallFreeContext(GPUContext); 728fa7b0802STobias Grosser IslNodeBuilder::finalize(); 729fa7b0802STobias Grosser } 730fa7b0802STobias Grosser 731fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() { 732abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory will directly send host pointers " 733abed4969SSiddharth Bhat "to the kernel. There is no need for device arrays"); 734fa7b0802STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 735fa7b0802STobias Grosser 736fa7b0802STobias Grosser for (int i = 0; i < Prog->n_array; ++i) { 737fa7b0802STobias Grosser gpu_array_info *Array = &Prog->array[i]; 73813c78e4dSTobias Grosser auto *ScopArray = (ScopArrayInfo *)Array->user; 7397287aeddSTobias Grosser std::string DevArrayName("p_dev_array_"); 7407287aeddSTobias Grosser DevArrayName.append(Array->name); 741fa7b0802STobias Grosser 74213c78e4dSTobias Grosser Value *ArraySize = getArraySize(Array); 743aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 744aaabbbf8STobias Grosser if (Offset) 745aaabbbf8STobias Grosser ArraySize = Builder.CreateSub( 746aaabbbf8STobias Grosser ArraySize, 747aaabbbf8STobias Grosser Builder.CreateMul(Offset, 748aaabbbf8STobias Grosser Builder.getInt64(ScopArray->getElemSizeInBytes()))); 7497287aeddSTobias Grosser Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 7507287aeddSTobias Grosser DevArray->setName(DevArrayName); 75113c78e4dSTobias Grosser DeviceAllocations[ScopArray] = DevArray; 752fa7b0802STobias Grosser } 753fa7b0802STobias Grosser 754fa7b0802STobias Grosser isl_ast_build_free(Build); 755fa7b0802STobias Grosser } 756fa7b0802STobias Grosser 757c1c6a2a6STobias Grosser void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 758c1c6a2a6STobias Grosser Value *BlockDimY, Value *BlockDimZ) { 759c1c6a2a6STobias Grosser auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 760c1c6a2a6STobias Grosser 761c1c6a2a6STobias Grosser for (auto &F : *M) { 762c1c6a2a6STobias Grosser if (F.getCallingConv() != CallingConv::PTX_Kernel) 763c1c6a2a6STobias Grosser continue; 764c1c6a2a6STobias Grosser 765c1c6a2a6STobias Grosser Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 766c1c6a2a6STobias Grosser 767c1c6a2a6STobias Grosser Metadata *Elements[] = { 768c1c6a2a6STobias Grosser ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 769c1c6a2a6STobias Grosser ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 770c1c6a2a6STobias Grosser ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 771c1c6a2a6STobias Grosser ValueAsMetadata::get(V[2]), 772c1c6a2a6STobias Grosser }; 773c1c6a2a6STobias Grosser MDNode *Node = MDNode::get(M->getContext(), Elements); 774c1c6a2a6STobias Grosser AnnotationNode->addOperand(Node); 775c1c6a2a6STobias Grosser } 776c1c6a2a6STobias Grosser } 777c1c6a2a6STobias Grosser 7787287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() { 779abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not use device arrays"); 78013c78e4dSTobias Grosser for (auto &Array : DeviceAllocations) 78113c78e4dSTobias Grosser createCallFreeDeviceMemory(Array.second); 7827287aeddSTobias Grosser } 7837287aeddSTobias Grosser 78457793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 78557793596STobias Grosser const char *Name = "polly_getKernel"; 78657793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 78757793596STobias Grosser Function *F = M->getFunction(Name); 78857793596STobias Grosser 78957793596STobias Grosser // If F is not available, declare it. 79057793596STobias Grosser if (!F) { 79157793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 79257793596STobias Grosser std::vector<Type *> Args; 79357793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79457793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 79557793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 79657793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 79757793596STobias Grosser } 79857793596STobias Grosser 79957793596STobias Grosser return Builder.CreateCall(F, {Buffer, Entry}); 80057793596STobias Grosser } 80157793596STobias Grosser 80279a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 80379a947c2STobias Grosser const char *Name = "polly_getDevicePtr"; 80479a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 80579a947c2STobias Grosser Function *F = M->getFunction(Name); 80679a947c2STobias Grosser 80779a947c2STobias Grosser // If F is not available, declare it. 80879a947c2STobias Grosser if (!F) { 80979a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 81079a947c2STobias Grosser std::vector<Type *> Args; 81179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 81279a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 81379a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 81479a947c2STobias Grosser } 81579a947c2STobias Grosser 81679a947c2STobias Grosser return Builder.CreateCall(F, {Allocation}); 81779a947c2STobias Grosser } 81879a947c2STobias Grosser 81979a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 82079a947c2STobias Grosser Value *GridDimY, Value *BlockDimX, 82179a947c2STobias Grosser Value *BlockDimY, Value *BlockDimZ, 82279a947c2STobias Grosser Value *Parameters) { 82379a947c2STobias Grosser const char *Name = "polly_launchKernel"; 82479a947c2STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 82579a947c2STobias Grosser Function *F = M->getFunction(Name); 82679a947c2STobias Grosser 82779a947c2STobias Grosser // If F is not available, declare it. 82879a947c2STobias Grosser if (!F) { 82979a947c2STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 83079a947c2STobias Grosser std::vector<Type *> Args; 83179a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 83279a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 83379a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 83479a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 83579a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 83679a947c2STobias Grosser Args.push_back(Builder.getInt32Ty()); 83779a947c2STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 83879a947c2STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 83979a947c2STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 84079a947c2STobias Grosser } 84179a947c2STobias Grosser 842ff40087aSTobias Grosser Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 84379a947c2STobias Grosser BlockDimZ, Parameters}); 84479a947c2STobias Grosser } 84579a947c2STobias Grosser 84657793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 84757793596STobias Grosser const char *Name = "polly_freeKernel"; 84857793596STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 84957793596STobias Grosser Function *F = M->getFunction(Name); 85057793596STobias Grosser 85157793596STobias Grosser // If F is not available, declare it. 85257793596STobias Grosser if (!F) { 85357793596STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 85457793596STobias Grosser std::vector<Type *> Args; 85557793596STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 85657793596STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 85757793596STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 85857793596STobias Grosser } 85957793596STobias Grosser 86057793596STobias Grosser Builder.CreateCall(F, {GPUKernel}); 86157793596STobias Grosser } 86257793596STobias Grosser 8637287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 864abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 865abed4969SSiddharth Bhat "for device"); 8667287aeddSTobias Grosser const char *Name = "polly_freeDeviceMemory"; 8677287aeddSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 8687287aeddSTobias Grosser Function *F = M->getFunction(Name); 8697287aeddSTobias Grosser 8707287aeddSTobias Grosser // If F is not available, declare it. 8717287aeddSTobias Grosser if (!F) { 8727287aeddSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 8737287aeddSTobias Grosser std::vector<Type *> Args; 8747287aeddSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 8757287aeddSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 8767287aeddSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 8777287aeddSTobias Grosser } 8787287aeddSTobias Grosser 8797287aeddSTobias Grosser Builder.CreateCall(F, {Array}); 8807287aeddSTobias Grosser } 8817287aeddSTobias Grosser 882fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 883abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not allocate or free memory " 884abed4969SSiddharth Bhat "for device"); 885fa7b0802STobias Grosser const char *Name = "polly_allocateMemoryForDevice"; 886fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 887fa7b0802STobias Grosser Function *F = M->getFunction(Name); 888fa7b0802STobias Grosser 889fa7b0802STobias Grosser // If F is not available, declare it. 890fa7b0802STobias Grosser if (!F) { 891fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 892fa7b0802STobias Grosser std::vector<Type *> Args; 893fa7b0802STobias Grosser Args.push_back(Builder.getInt64Ty()); 894fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 895fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 896fa7b0802STobias Grosser } 897fa7b0802STobias Grosser 898fa7b0802STobias Grosser return Builder.CreateCall(F, {Size}); 899fa7b0802STobias Grosser } 900fa7b0802STobias Grosser 90113c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 90213c78e4dSTobias Grosser Value *DeviceData, 90313c78e4dSTobias Grosser Value *Size) { 904abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 905abed4969SSiddharth Bhat "device and host"); 90613c78e4dSTobias Grosser const char *Name = "polly_copyFromHostToDevice"; 90713c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 90813c78e4dSTobias Grosser Function *F = M->getFunction(Name); 90913c78e4dSTobias Grosser 91013c78e4dSTobias Grosser // If F is not available, declare it. 91113c78e4dSTobias Grosser if (!F) { 91213c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 91313c78e4dSTobias Grosser std::vector<Type *> Args; 91413c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91513c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 91613c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 91713c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 91813c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 91913c78e4dSTobias Grosser } 92013c78e4dSTobias Grosser 92113c78e4dSTobias Grosser Builder.CreateCall(F, {HostData, DeviceData, Size}); 92213c78e4dSTobias Grosser } 92313c78e4dSTobias Grosser 92413c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 92513c78e4dSTobias Grosser Value *HostData, 92613c78e4dSTobias Grosser Value *Size) { 927abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory does not transfer memory between " 928abed4969SSiddharth Bhat "device and host"); 92913c78e4dSTobias Grosser const char *Name = "polly_copyFromDeviceToHost"; 93013c78e4dSTobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 93113c78e4dSTobias Grosser Function *F = M->getFunction(Name); 93213c78e4dSTobias Grosser 93313c78e4dSTobias Grosser // If F is not available, declare it. 93413c78e4dSTobias Grosser if (!F) { 93513c78e4dSTobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 93613c78e4dSTobias Grosser std::vector<Type *> Args; 93713c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93813c78e4dSTobias Grosser Args.push_back(Builder.getInt8PtrTy()); 93913c78e4dSTobias Grosser Args.push_back(Builder.getInt64Ty()); 94013c78e4dSTobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 94113c78e4dSTobias Grosser F = Function::Create(Ty, Linkage, Name, M); 94213c78e4dSTobias Grosser } 94313c78e4dSTobias Grosser 94413c78e4dSTobias Grosser Builder.CreateCall(F, {DeviceData, HostData, Size}); 94513c78e4dSTobias Grosser } 94613c78e4dSTobias Grosser 947abed4969SSiddharth Bhat void GPUNodeBuilder::createCallSynchronizeDevice() { 948abed4969SSiddharth Bhat assert(ManagedMemory && "explicit synchronization is only necessary for " 949abed4969SSiddharth Bhat "managed memory"); 950abed4969SSiddharth Bhat const char *Name = "polly_synchronizeDevice"; 951abed4969SSiddharth Bhat Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 952abed4969SSiddharth Bhat Function *F = M->getFunction(Name); 953abed4969SSiddharth Bhat 954abed4969SSiddharth Bhat // If F is not available, declare it. 955abed4969SSiddharth Bhat if (!F) { 956abed4969SSiddharth Bhat GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 957abed4969SSiddharth Bhat FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 958abed4969SSiddharth Bhat F = Function::Create(Ty, Linkage, Name, M); 959abed4969SSiddharth Bhat } 960abed4969SSiddharth Bhat 961abed4969SSiddharth Bhat Builder.CreateCall(F); 962abed4969SSiddharth Bhat } 963abed4969SSiddharth Bhat 964fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() { 96517f01968SSiddharth Bhat const char *Name; 96617f01968SSiddharth Bhat 96717f01968SSiddharth Bhat switch (Runtime) { 96817f01968SSiddharth Bhat case GPURuntime::CUDA: 96917f01968SSiddharth Bhat Name = "polly_initContextCUDA"; 97017f01968SSiddharth Bhat break; 97117f01968SSiddharth Bhat case GPURuntime::OpenCL: 97217f01968SSiddharth Bhat Name = "polly_initContextCL"; 97317f01968SSiddharth Bhat break; 97417f01968SSiddharth Bhat } 97517f01968SSiddharth Bhat 976fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 977fa7b0802STobias Grosser Function *F = M->getFunction(Name); 978fa7b0802STobias Grosser 979fa7b0802STobias Grosser // If F is not available, declare it. 980fa7b0802STobias Grosser if (!F) { 981fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 982fa7b0802STobias Grosser std::vector<Type *> Args; 983fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 984fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 985fa7b0802STobias Grosser } 986fa7b0802STobias Grosser 987fa7b0802STobias Grosser return Builder.CreateCall(F, {}); 988fa7b0802STobias Grosser } 989fa7b0802STobias Grosser 990fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) { 991fa7b0802STobias Grosser const char *Name = "polly_freeContext"; 992fa7b0802STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 993fa7b0802STobias Grosser Function *F = M->getFunction(Name); 994fa7b0802STobias Grosser 995fa7b0802STobias Grosser // If F is not available, declare it. 996fa7b0802STobias Grosser if (!F) { 997fa7b0802STobias Grosser GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 998fa7b0802STobias Grosser std::vector<Type *> Args; 999fa7b0802STobias Grosser Args.push_back(Builder.getInt8PtrTy()); 1000fa7b0802STobias Grosser FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1001fa7b0802STobias Grosser F = Function::Create(Ty, Linkage, Name, M); 1002fa7b0802STobias Grosser } 1003fa7b0802STobias Grosser 1004fa7b0802STobias Grosser Builder.CreateCall(F, {Context}); 1005fa7b0802STobias Grosser } 1006fa7b0802STobias Grosser 10075260c041STobias Grosser /// Check if one string is a prefix of another. 10085260c041STobias Grosser /// 10095260c041STobias Grosser /// @param String The string in which to look for the prefix. 10105260c041STobias Grosser /// @param Prefix The prefix to look for. 10115260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) { 10125260c041STobias Grosser return String.find(Prefix) == 0; 10135260c041STobias Grosser } 10145260c041STobias Grosser 101513c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 101613c78e4dSTobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 101713c78e4dSTobias Grosser Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 101813c78e4dSTobias Grosser 101913c78e4dSTobias Grosser if (!gpu_array_is_scalar(Array)) { 10209e3db2b7SSiddharth Bhat auto OffsetDimZero = isl_multi_pw_aff_get_pw_aff(Array->bound, 0); 102113c78e4dSTobias Grosser isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 102213c78e4dSTobias Grosser 102313c78e4dSTobias Grosser for (unsigned int i = 1; i < Array->n_index; i++) { 10249e3db2b7SSiddharth Bhat isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i); 102513c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 102613c78e4dSTobias Grosser Res = isl_ast_expr_mul(Res, Expr); 102713c78e4dSTobias Grosser } 102813c78e4dSTobias Grosser 102913c78e4dSTobias Grosser Value *NumElements = ExprBuilder.create(Res); 1030b79f4d39STobias Grosser if (NumElements->getType() != ArraySize->getType()) 1031b79f4d39STobias Grosser NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 103213c78e4dSTobias Grosser ArraySize = Builder.CreateMul(ArraySize, NumElements); 103313c78e4dSTobias Grosser } 103413c78e4dSTobias Grosser isl_ast_build_free(Build); 103513c78e4dSTobias Grosser return ArraySize; 103613c78e4dSTobias Grosser } 103713c78e4dSTobias Grosser 1038aaabbbf8STobias Grosser Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1039aaabbbf8STobias Grosser if (gpu_array_is_scalar(Array)) 1040aaabbbf8STobias Grosser return nullptr; 1041aaabbbf8STobias Grosser 1042aaabbbf8STobias Grosser isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1043aaabbbf8STobias Grosser 1044aaabbbf8STobias Grosser isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1045aaabbbf8STobias Grosser 1046aaabbbf8STobias Grosser isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1047aaabbbf8STobias Grosser 1048aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1049aaabbbf8STobias Grosser ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1050aaabbbf8STobias Grosser 1051aaabbbf8STobias Grosser if (isl_set_is_subset(Min, ZeroSet)) { 1052aaabbbf8STobias Grosser isl_set_free(Min); 1053aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1054aaabbbf8STobias Grosser isl_ast_build_free(Build); 1055aaabbbf8STobias Grosser return nullptr; 1056aaabbbf8STobias Grosser } 1057aaabbbf8STobias Grosser isl_set_free(ZeroSet); 1058aaabbbf8STobias Grosser 1059aaabbbf8STobias Grosser isl_ast_expr *Result = 1060aaabbbf8STobias Grosser isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1061aaabbbf8STobias Grosser 1062aaabbbf8STobias Grosser for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1063aaabbbf8STobias Grosser if (i > 0) { 10649e3db2b7SSiddharth Bhat isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1); 1065aaabbbf8STobias Grosser isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1066aaabbbf8STobias Grosser Result = isl_ast_expr_mul(Result, BExpr); 1067aaabbbf8STobias Grosser } 1068aaabbbf8STobias Grosser isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1069aaabbbf8STobias Grosser isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1070aaabbbf8STobias Grosser Result = isl_ast_expr_add(Result, MExpr); 1071aaabbbf8STobias Grosser } 1072aaabbbf8STobias Grosser 1073aaabbbf8STobias Grosser Value *ResultValue = ExprBuilder.create(Result); 1074aaabbbf8STobias Grosser isl_set_free(Min); 1075aaabbbf8STobias Grosser isl_ast_build_free(Build); 1076aaabbbf8STobias Grosser 1077aaabbbf8STobias Grosser return ResultValue; 1078aaabbbf8STobias Grosser } 1079aaabbbf8STobias Grosser 1080abed4969SSiddharth Bhat Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1081abed4969SSiddharth Bhat ScopArrayInfo *ArrayInfo) { 1082abed4969SSiddharth Bhat 1083abed4969SSiddharth Bhat assert(ManagedMemory && "Only used when you wish to get a host " 1084abed4969SSiddharth Bhat "pointer for sending data to the kernel, " 1085abed4969SSiddharth Bhat "with managed memory"); 1086abed4969SSiddharth Bhat std::map<ScopArrayInfo *, Value *>::iterator it; 1087abed4969SSiddharth Bhat if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1088abed4969SSiddharth Bhat return it->second; 1089abed4969SSiddharth Bhat } else { 1090abed4969SSiddharth Bhat Value *HostPtr; 1091abed4969SSiddharth Bhat 1092abed4969SSiddharth Bhat if (gpu_array_is_scalar(Array)) 1093abed4969SSiddharth Bhat HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1094abed4969SSiddharth Bhat else 1095abed4969SSiddharth Bhat HostPtr = ArrayInfo->getBasePtr(); 1096abed4969SSiddharth Bhat 1097abed4969SSiddharth Bhat Value *Offset = getArrayOffset(Array); 1098abed4969SSiddharth Bhat if (Offset) { 1099abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast( 1100abed4969SSiddharth Bhat HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1101abed4969SSiddharth Bhat HostPtr = Builder.CreateGEP(HostPtr, Offset); 1102abed4969SSiddharth Bhat } 1103abed4969SSiddharth Bhat 1104abed4969SSiddharth Bhat HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1105abed4969SSiddharth Bhat DeviceAllocations[ArrayInfo] = HostPtr; 1106abed4969SSiddharth Bhat return HostPtr; 1107abed4969SSiddharth Bhat } 1108abed4969SSiddharth Bhat } 1109abed4969SSiddharth Bhat 111013c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 111113c78e4dSTobias Grosser enum DataDirection Direction) { 1112abed4969SSiddharth Bhat assert(!ManagedMemory && "Managed memory needs no data transfers"); 111313c78e4dSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 111413c78e4dSTobias Grosser isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 111513c78e4dSTobias Grosser isl_id *Id = isl_ast_expr_get_id(Arg); 111613c78e4dSTobias Grosser auto Array = (gpu_array_info *)isl_id_get_user(Id); 111713c78e4dSTobias Grosser auto ScopArray = (ScopArrayInfo *)(Array->user); 111813c78e4dSTobias Grosser 111913c78e4dSTobias Grosser Value *Size = getArraySize(Array); 1120aaabbbf8STobias Grosser Value *Offset = getArrayOffset(Array); 112113c78e4dSTobias Grosser Value *DevPtr = DeviceAllocations[ScopArray]; 112213c78e4dSTobias Grosser 1123b06ff457STobias Grosser Value *HostPtr; 1124b06ff457STobias Grosser 1125b06ff457STobias Grosser if (gpu_array_is_scalar(Array)) 1126b06ff457STobias Grosser HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1127b06ff457STobias Grosser else 1128b06ff457STobias Grosser HostPtr = ScopArray->getBasePtr(); 112913c78e4dSTobias Grosser 1130aaabbbf8STobias Grosser if (Offset) { 1131aaabbbf8STobias Grosser HostPtr = Builder.CreatePointerCast( 1132aaabbbf8STobias Grosser HostPtr, ScopArray->getElementType()->getPointerTo()); 1133aaabbbf8STobias Grosser HostPtr = Builder.CreateGEP(HostPtr, Offset); 1134aaabbbf8STobias Grosser } 1135aaabbbf8STobias Grosser 113613c78e4dSTobias Grosser HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 113713c78e4dSTobias Grosser 1138aaabbbf8STobias Grosser if (Offset) { 1139aaabbbf8STobias Grosser Size = Builder.CreateSub( 1140ff40087aSTobias Grosser Size, Builder.CreateMul( 1141ff40087aSTobias Grosser Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1142aaabbbf8STobias Grosser } 1143aaabbbf8STobias Grosser 114413c78e4dSTobias Grosser if (Direction == HOST_TO_DEVICE) 114513c78e4dSTobias Grosser createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 114613c78e4dSTobias Grosser else 114713c78e4dSTobias Grosser createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 114813c78e4dSTobias Grosser 114913c78e4dSTobias Grosser isl_id_free(Id); 115013c78e4dSTobias Grosser isl_ast_expr_free(Arg); 115113c78e4dSTobias Grosser isl_ast_expr_free(Expr); 115213c78e4dSTobias Grosser isl_ast_node_free(TransferStmt); 115313c78e4dSTobias Grosser } 115413c78e4dSTobias Grosser 11551fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 115632837fe3STobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 115732837fe3STobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 115832837fe3STobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 115932837fe3STobias Grosser isl_id_free(Id); 116032837fe3STobias Grosser isl_ast_expr_free(StmtExpr); 116132837fe3STobias Grosser 116232837fe3STobias Grosser const char *Str = isl_id_get_name(Id); 116332837fe3STobias Grosser if (!strcmp(Str, "kernel")) { 116432837fe3STobias Grosser createKernel(UserStmt); 116532837fe3STobias Grosser isl_ast_expr_free(Expr); 116632837fe3STobias Grosser return; 116732837fe3STobias Grosser } 11689e3db2b7SSiddharth Bhat if (!strcmp(Str, "init_device")) { 11699e3db2b7SSiddharth Bhat initializeAfterRTH(); 11709e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 11719e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 11729e3db2b7SSiddharth Bhat return; 11739e3db2b7SSiddharth Bhat } 11749e3db2b7SSiddharth Bhat if (!strcmp(Str, "clear_device")) { 11759e3db2b7SSiddharth Bhat finalize(); 11769e3db2b7SSiddharth Bhat isl_ast_node_free(UserStmt); 11779e3db2b7SSiddharth Bhat isl_ast_expr_free(Expr); 11789e3db2b7SSiddharth Bhat return; 11799e3db2b7SSiddharth Bhat } 118013c78e4dSTobias Grosser if (isPrefix(Str, "to_device")) { 1181abed4969SSiddharth Bhat if (!ManagedMemory) 118213c78e4dSTobias Grosser createDataTransfer(UserStmt, HOST_TO_DEVICE); 1183abed4969SSiddharth Bhat else 1184abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1185abed4969SSiddharth Bhat 118632837fe3STobias Grosser isl_ast_expr_free(Expr); 118713c78e4dSTobias Grosser return; 118813c78e4dSTobias Grosser } 118913c78e4dSTobias Grosser 119013c78e4dSTobias Grosser if (isPrefix(Str, "from_device")) { 1191abed4969SSiddharth Bhat if (!ManagedMemory) { 119213c78e4dSTobias Grosser createDataTransfer(UserStmt, DEVICE_TO_HOST); 1193abed4969SSiddharth Bhat } else { 1194abed4969SSiddharth Bhat createCallSynchronizeDevice(); 1195abed4969SSiddharth Bhat isl_ast_node_free(UserStmt); 1196abed4969SSiddharth Bhat } 119713c78e4dSTobias Grosser isl_ast_expr_free(Expr); 119838fc0aedSTobias Grosser return; 119938fc0aedSTobias Grosser } 120038fc0aedSTobias Grosser 12015260c041STobias Grosser isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 12025260c041STobias Grosser struct ppcg_kernel_stmt *KernelStmt = 12035260c041STobias Grosser (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 12045260c041STobias Grosser isl_id_free(Anno); 12055260c041STobias Grosser 12065260c041STobias Grosser switch (KernelStmt->type) { 12075260c041STobias Grosser case ppcg_kernel_domain: 1208edb885cbSTobias Grosser createScopStmt(Expr, KernelStmt); 12095260c041STobias Grosser isl_ast_node_free(UserStmt); 12105260c041STobias Grosser return; 12115260c041STobias Grosser case ppcg_kernel_copy: 1212b513b491STobias Grosser createKernelCopy(KernelStmt); 12135260c041STobias Grosser isl_ast_expr_free(Expr); 12145260c041STobias Grosser isl_ast_node_free(UserStmt); 12155260c041STobias Grosser return; 12165260c041STobias Grosser case ppcg_kernel_sync: 12175260c041STobias Grosser createKernelSync(); 12185260c041STobias Grosser isl_ast_expr_free(Expr); 12195260c041STobias Grosser isl_ast_node_free(UserStmt); 12205260c041STobias Grosser return; 12215260c041STobias Grosser } 12225260c041STobias Grosser 12235260c041STobias Grosser isl_ast_expr_free(Expr); 12245260c041STobias Grosser isl_ast_node_free(UserStmt); 12255260c041STobias Grosser return; 12265260c041STobias Grosser } 1227b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1228b513b491STobias Grosser isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1229b513b491STobias Grosser LocalIndex = isl_ast_expr_address_of(LocalIndex); 1230b513b491STobias Grosser Value *LocalAddr = ExprBuilder.create(LocalIndex); 1231b513b491STobias Grosser isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1232b513b491STobias Grosser Index = isl_ast_expr_address_of(Index); 1233b513b491STobias Grosser Value *GlobalAddr = ExprBuilder.create(Index); 1234b513b491STobias Grosser 1235b513b491STobias Grosser if (KernelStmt->u.c.read) { 1236b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1237b513b491STobias Grosser Builder.CreateStore(Load, LocalAddr); 1238b513b491STobias Grosser } else { 1239b513b491STobias Grosser LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1240b513b491STobias Grosser Builder.CreateStore(Load, GlobalAddr); 1241b513b491STobias Grosser } 1242b513b491STobias Grosser } 12435260c041STobias Grosser 1244edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1245edb885cbSTobias Grosser ppcg_kernel_stmt *KernelStmt) { 1246edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1247edb885cbSTobias Grosser isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1248edb885cbSTobias Grosser 1249edb885cbSTobias Grosser LoopToScevMapT LTS; 1250edb885cbSTobias Grosser LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1251edb885cbSTobias Grosser 1252edb885cbSTobias Grosser createSubstitutions(Expr, Stmt, LTS); 1253edb885cbSTobias Grosser 1254edb885cbSTobias Grosser if (Stmt->isBlockStmt()) 1255edb885cbSTobias Grosser BlockGen.copyStmt(*Stmt, LTS, Indexes); 1256edb885cbSTobias Grosser else 1257a82c4b5dSTobias Grosser RegionGen.copyStmt(*Stmt, LTS, Indexes); 1258edb885cbSTobias Grosser } 1259edb885cbSTobias Grosser 12605260c041STobias Grosser void GPUNodeBuilder::createKernelSync() { 12615260c041STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12622f3073b5SPhilipp Schaad const char *SpirName = "__gen_ocl_barrier_global"; 126317f01968SSiddharth Bhat 126417f01968SSiddharth Bhat Function *Sync; 126517f01968SSiddharth Bhat 126617f01968SSiddharth Bhat switch (Arch) { 12672f3073b5SPhilipp Schaad case GPUArch::SPIR64: 12682f3073b5SPhilipp Schaad case GPUArch::SPIR32: 12692f3073b5SPhilipp Schaad Sync = M->getFunction(SpirName); 12702f3073b5SPhilipp Schaad 12712f3073b5SPhilipp Schaad // If Sync is not available, declare it. 12722f3073b5SPhilipp Schaad if (!Sync) { 12732f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 12742f3073b5SPhilipp Schaad std::vector<Type *> Args; 12752f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 12762f3073b5SPhilipp Schaad Sync = Function::Create(Ty, Linkage, SpirName, M); 12772f3073b5SPhilipp Schaad Sync->setCallingConv(CallingConv::SPIR_FUNC); 12782f3073b5SPhilipp Schaad } 12792f3073b5SPhilipp Schaad break; 128017f01968SSiddharth Bhat case GPUArch::NVPTX64: 128117f01968SSiddharth Bhat Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 128217f01968SSiddharth Bhat break; 128317f01968SSiddharth Bhat } 128417f01968SSiddharth Bhat 12855260c041STobias Grosser Builder.CreateCall(Sync, {}); 12865260c041STobias Grosser } 12875260c041STobias Grosser 1288edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node 1289edb885cbSTobias Grosser /// 1290edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring 1291edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore. 1292edb885cbSTobias Grosser /// 1293edb885cbSTobias Grosser /// @param Node The node to collect references for. 1294edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected. 1295edb885cbSTobias Grosser /// 1296edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully. 1297edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1298edb885cbSTobias Grosser if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1299edb885cbSTobias Grosser return isl_bool_true; 1300edb885cbSTobias Grosser 1301edb885cbSTobias Grosser isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1302edb885cbSTobias Grosser isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1303edb885cbSTobias Grosser isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1304edb885cbSTobias Grosser const char *Str = isl_id_get_name(Id); 1305edb885cbSTobias Grosser isl_id_free(Id); 1306edb885cbSTobias Grosser isl_ast_expr_free(StmtExpr); 1307edb885cbSTobias Grosser isl_ast_expr_free(Expr); 1308edb885cbSTobias Grosser 1309edb885cbSTobias Grosser if (!isPrefix(Str, "Stmt")) 1310edb885cbSTobias Grosser return isl_bool_true; 1311edb885cbSTobias Grosser 1312edb885cbSTobias Grosser Id = isl_ast_node_get_annotation(Node); 1313edb885cbSTobias Grosser auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1314edb885cbSTobias Grosser auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1315edb885cbSTobias Grosser isl_id_free(Id); 1316edb885cbSTobias Grosser 131700bb5a99STobias Grosser addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1318edb885cbSTobias Grosser 1319edb885cbSTobias Grosser return isl_bool_true; 1320edb885cbSTobias Grosser } 1321edb885cbSTobias Grosser 1322f291c8d5SSiddharth Bhat /// Check if F is a function that we can code-generate in a GPU kernel. 1323f291c8d5SSiddharth Bhat static bool isValidFunctionInKernel(llvm::Function *F) { 1324f291c8d5SSiddharth Bhat assert(F && "F is an invalid pointer"); 1325f291c8d5SSiddharth Bhat // We string compare against the name of the function to allow 132654491db6STobias Grosser // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 132754491db6STobias Grosser // "llvm.copysign". 132854491db6STobias Grosser const StringRef Name = F->getName(); 132954491db6STobias Grosser return F->isIntrinsic() && 133054491db6STobias Grosser (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 133154491db6STobias Grosser Name.startswith("llvm.copysign")); 1332f291c8d5SSiddharth Bhat } 1333f291c8d5SSiddharth Bhat 1334f291c8d5SSiddharth Bhat /// Do not take `Function` as a subtree value. 1335f291c8d5SSiddharth Bhat /// 1336f291c8d5SSiddharth Bhat /// We try to take the reference of all subtree values and pass them along 1337f291c8d5SSiddharth Bhat /// to the kernel from the host. Taking an address of any function and 1338f291c8d5SSiddharth Bhat /// trying to pass along is nonsensical. Only allow `Value`s that are not 1339f291c8d5SSiddharth Bhat /// `Function`s. 1340f291c8d5SSiddharth Bhat static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1341f291c8d5SSiddharth Bhat 1342f291c8d5SSiddharth Bhat /// Return `Function`s from `RawSubtreeValues`. 1343f291c8d5SSiddharth Bhat static SetVector<Function *> 1344f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1345f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1346f291c8d5SSiddharth Bhat for (Value *It : RawSubtreeValues) { 1347f291c8d5SSiddharth Bhat Function *F = dyn_cast<Function>(It); 1348f291c8d5SSiddharth Bhat if (F) { 1349f291c8d5SSiddharth Bhat assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1350f291c8d5SSiddharth Bhat "this point if an invalid function " 1351f291c8d5SSiddharth Bhat "were present in a kernel."); 1352f291c8d5SSiddharth Bhat SubtreeFunctions.insert(F); 1353f291c8d5SSiddharth Bhat } 1354f291c8d5SSiddharth Bhat } 1355f291c8d5SSiddharth Bhat return SubtreeFunctions; 1356f291c8d5SSiddharth Bhat } 1357f291c8d5SSiddharth Bhat 1358f291c8d5SSiddharth Bhat std::pair<SetVector<Value *>, SetVector<Function *>> 1359f291c8d5SSiddharth Bhat GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1360edb885cbSTobias Grosser SetVector<Value *> SubtreeValues; 1361edb885cbSTobias Grosser SetVector<const SCEV *> SCEVs; 1362edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1363edb885cbSTobias Grosser SubtreeReferences References = { 1364edb885cbSTobias Grosser LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1365edb885cbSTobias Grosser 1366edb885cbSTobias Grosser for (const auto &I : IDToValue) 1367edb885cbSTobias Grosser SubtreeValues.insert(I.second); 1368edb885cbSTobias Grosser 1369edb885cbSTobias Grosser isl_ast_node_foreach_descendant_top_down( 1370edb885cbSTobias Grosser Kernel->tree, collectReferencesInGPUStmt, &References); 1371edb885cbSTobias Grosser 1372edb885cbSTobias Grosser for (const SCEV *Expr : SCEVs) 1373edb885cbSTobias Grosser findValues(Expr, SE, SubtreeValues); 1374edb885cbSTobias Grosser 1375edb885cbSTobias Grosser for (auto &SAI : S.arrays()) 1376d7754a12SRoman Gareev SubtreeValues.remove(SAI->getBasePtr()); 1377edb885cbSTobias Grosser 1378edb885cbSTobias Grosser isl_space *Space = S.getParamSpace(); 1379edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1380edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1381edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1382edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1383edb885cbSTobias Grosser SubtreeValues.remove(Val); 1384edb885cbSTobias Grosser isl_id_free(Id); 1385edb885cbSTobias Grosser } 1386edb885cbSTobias Grosser isl_space_free(Space); 1387edb885cbSTobias Grosser 1388edb885cbSTobias Grosser for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1389edb885cbSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1390edb885cbSTobias Grosser assert(IDToValue.count(Id)); 1391edb885cbSTobias Grosser Value *Val = IDToValue[Id]; 1392edb885cbSTobias Grosser SubtreeValues.remove(Val); 1393edb885cbSTobias Grosser isl_id_free(Id); 1394edb885cbSTobias Grosser } 1395edb885cbSTobias Grosser 1396f291c8d5SSiddharth Bhat // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1397f291c8d5SSiddharth Bhat // SubtreeValues. This is important, because we should not lose any 1398f291c8d5SSiddharth Bhat // SubtreeValues in the process of constructing the 1399f291c8d5SSiddharth Bhat // "ValidSubtree{Values, Functions} sets. Nor should the set 1400f291c8d5SSiddharth Bhat // ValidSubtree{Values, Functions} have any common element. 1401f291c8d5SSiddharth Bhat auto ValidSubtreeValuesIt = 1402f291c8d5SSiddharth Bhat make_filter_range(SubtreeValues, isValidSubtreeValue); 1403f291c8d5SSiddharth Bhat SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1404f291c8d5SSiddharth Bhat ValidSubtreeValuesIt.end()); 1405f291c8d5SSiddharth Bhat SetVector<Function *> ValidSubtreeFunctions( 1406f291c8d5SSiddharth Bhat getFunctionsFromRawSubtreeValues(SubtreeValues)); 1407f291c8d5SSiddharth Bhat 1408a1b2086aSSiddharth Bhat // @see IslNodeBuilder::getReferencesInSubtree 1409a1b2086aSSiddharth Bhat SetVector<Value *> ReplacedValues; 1410a1b2086aSSiddharth Bhat for (Value *V : ValidSubtreeValues) { 1411a1b2086aSSiddharth Bhat auto It = ValueMap.find(V); 1412a1b2086aSSiddharth Bhat if (It == ValueMap.end()) 1413a1b2086aSSiddharth Bhat ReplacedValues.insert(V); 1414a1b2086aSSiddharth Bhat else 1415a1b2086aSSiddharth Bhat ReplacedValues.insert(It->second); 1416a1b2086aSSiddharth Bhat } 1417a1b2086aSSiddharth Bhat return std::make_pair(ReplacedValues, ValidSubtreeFunctions); 1418edb885cbSTobias Grosser } 1419edb885cbSTobias Grosser 142074dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) { 142174dc3cb4STobias Grosser DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 142274dc3cb4STobias Grosser std::vector<BasicBlock *> Nodes; 142374dc3cb4STobias Grosser for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 142474dc3cb4STobias Grosser Nodes.push_back(I->getBlock()); 142574dc3cb4STobias Grosser 142674dc3cb4STobias Grosser for (BasicBlock *BB : Nodes) 142774dc3cb4STobias Grosser DT.eraseNode(BB); 142874dc3cb4STobias Grosser } 142974dc3cb4STobias Grosser 143074dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) { 143174dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 143274dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 143374dc3cb4STobias Grosser if (L) 143474dc3cb4STobias Grosser SE.forgetLoop(L); 143574dc3cb4STobias Grosser } 143674dc3cb4STobias Grosser } 143774dc3cb4STobias Grosser 143874dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) { 143974dc3cb4STobias Grosser for (BasicBlock &BB : *F) { 144074dc3cb4STobias Grosser Loop *L = LI.getLoopFor(&BB); 144174dc3cb4STobias Grosser if (L) 144274dc3cb4STobias Grosser SE.forgetLoop(L); 144374dc3cb4STobias Grosser LI.removeBlock(&BB); 144474dc3cb4STobias Grosser } 144574dc3cb4STobias Grosser } 144674dc3cb4STobias Grosser 144779a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 144879a947c2STobias Grosser std::vector<Value *> Sizes; 144979a947c2STobias Grosser isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 145079a947c2STobias Grosser 145179a947c2STobias Grosser for (long i = 0; i < Kernel->n_grid; i++) { 145279a947c2STobias Grosser isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 145379a947c2STobias Grosser isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 145479a947c2STobias Grosser Value *Res = ExprBuilder.create(GridSize); 145579a947c2STobias Grosser Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 145679a947c2STobias Grosser Sizes.push_back(Res); 145779a947c2STobias Grosser } 145879a947c2STobias Grosser isl_ast_build_free(Context); 145979a947c2STobias Grosser 146079a947c2STobias Grosser for (long i = Kernel->n_grid; i < 3; i++) 146179a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 146279a947c2STobias Grosser 146379a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1]); 146479a947c2STobias Grosser } 146579a947c2STobias Grosser 146679a947c2STobias Grosser std::tuple<Value *, Value *, Value *> 146779a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 146879a947c2STobias Grosser std::vector<Value *> Sizes; 146979a947c2STobias Grosser 147079a947c2STobias Grosser for (long i = 0; i < Kernel->n_block; i++) { 147179a947c2STobias Grosser Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 147279a947c2STobias Grosser Sizes.push_back(Res); 147379a947c2STobias Grosser } 147479a947c2STobias Grosser 147579a947c2STobias Grosser for (long i = Kernel->n_block; i < 3; i++) 147679a947c2STobias Grosser Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 147779a947c2STobias Grosser 147879a947c2STobias Grosser return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 147979a947c2STobias Grosser } 148079a947c2STobias Grosser 1481a90be207SSiddharth Bhat void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1482a90be207SSiddharth Bhat Instruction *Param, int Index) { 1483a90be207SSiddharth Bhat Value *Slot = Builder.CreateGEP( 1484a90be207SSiddharth Bhat Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1485a90be207SSiddharth Bhat Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1486a90be207SSiddharth Bhat Builder.CreateStore(ParamTyped, Slot); 1487a90be207SSiddharth Bhat } 1488a90be207SSiddharth Bhat 148957693272STobias Grosser Value * 149057693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 149157693272STobias Grosser SetVector<Value *> SubtreeValues) { 1492a90be207SSiddharth Bhat const int NumArgs = F->arg_size(); 1493a90be207SSiddharth Bhat std::vector<int> ArgSizes(NumArgs); 1494a90be207SSiddharth Bhat 1495a90be207SSiddharth Bhat Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 149679a947c2STobias Grosser 149779a947c2STobias Grosser BasicBlock *EntryBlock = 149879a947c2STobias Grosser &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 149967726b32STobias Grosser auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 150079a947c2STobias Grosser std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 150167726b32STobias Grosser Instruction *Parameters = new AllocaInst( 150267726b32STobias Grosser ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 150379a947c2STobias Grosser 150479a947c2STobias Grosser int Index = 0; 150579a947c2STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 150679a947c2STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 150779a947c2STobias Grosser continue; 150879a947c2STobias Grosser 150979a947c2STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 151079a947c2STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 151179a947c2STobias Grosser 1512a90be207SSiddharth Bhat ArgSizes[Index] = SAI->getElemSizeInBytes(); 1513a90be207SSiddharth Bhat 1514abed4969SSiddharth Bhat Value *DevArray = nullptr; 1515abed4969SSiddharth Bhat if (ManagedMemory) { 1516abed4969SSiddharth Bhat DevArray = getOrCreateManagedDeviceArray( 1517abed4969SSiddharth Bhat &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1518abed4969SSiddharth Bhat } else { 1519abed4969SSiddharth Bhat DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 152079a947c2STobias Grosser DevArray = createCallGetDevicePtr(DevArray); 1521abed4969SSiddharth Bhat } 1522abed4969SSiddharth Bhat assert(DevArray != nullptr && "Array to be offloaded to device not " 1523abed4969SSiddharth Bhat "initialized"); 1524aaabbbf8STobias Grosser Value *Offset = getArrayOffset(&Prog->array[i]); 1525aaabbbf8STobias Grosser 1526aaabbbf8STobias Grosser if (Offset) { 1527aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast( 1528aaabbbf8STobias Grosser DevArray, SAI->getElementType()->getPointerTo()); 1529aaabbbf8STobias Grosser DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1530aaabbbf8STobias Grosser DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1531aaabbbf8STobias Grosser } 1532fe74a7a1STobias Grosser Value *Slot = Builder.CreateGEP( 1533fe74a7a1STobias Grosser Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1534aaabbbf8STobias Grosser 1535fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1536abed4969SSiddharth Bhat Value *ValPtr = nullptr; 1537abed4969SSiddharth Bhat if (ManagedMemory) 1538abed4969SSiddharth Bhat ValPtr = DevArray; 1539abed4969SSiddharth Bhat else 1540abed4969SSiddharth Bhat ValPtr = BlockGen.getOrCreateAlloca(SAI); 1541abed4969SSiddharth Bhat 1542abed4969SSiddharth Bhat assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1543abed4969SSiddharth Bhat " to be stored into Parameters"); 1544fe74a7a1STobias Grosser Value *ValPtrCast = 1545fe74a7a1STobias Grosser Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1546fe74a7a1STobias Grosser Builder.CreateStore(ValPtrCast, Slot); 1547fe74a7a1STobias Grosser } else { 154867726b32STobias Grosser Instruction *Param = 154967726b32STobias Grosser new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 155067726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 155179a947c2STobias Grosser EntryBlock->getTerminator()); 155279a947c2STobias Grosser Builder.CreateStore(DevArray, Param); 155379a947c2STobias Grosser Value *ParamTyped = 155479a947c2STobias Grosser Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 155579a947c2STobias Grosser Builder.CreateStore(ParamTyped, Slot); 1556fe74a7a1STobias Grosser } 155779a947c2STobias Grosser Index++; 155879a947c2STobias Grosser } 155979a947c2STobias Grosser 1560a490147cSTobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1561a490147cSTobias Grosser 1562a490147cSTobias Grosser for (long i = 0; i < NumHostIters; i++) { 1563a490147cSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1564a490147cSTobias Grosser Value *Val = IDToValue[Id]; 1565a490147cSTobias Grosser isl_id_free(Id); 1566a90be207SSiddharth Bhat 1567a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1568a90be207SSiddharth Bhat 156967726b32STobias Grosser Instruction *Param = 157067726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 157167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1572a490147cSTobias Grosser EntryBlock->getTerminator()); 1573a490147cSTobias Grosser Builder.CreateStore(Val, Param); 1574a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1575a490147cSTobias Grosser Index++; 1576a490147cSTobias Grosser } 1577a490147cSTobias Grosser 1578d8b94bcaSTobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1579d8b94bcaSTobias Grosser 1580d8b94bcaSTobias Grosser for (long i = 0; i < NumVars; i++) { 1581d8b94bcaSTobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1582d8b94bcaSTobias Grosser Value *Val = IDToValue[Id]; 1583a1b2086aSSiddharth Bhat if (ValueMap.count(Val)) 1584a1b2086aSSiddharth Bhat Val = ValueMap[Val]; 1585d8b94bcaSTobias Grosser isl_id_free(Id); 1586a90be207SSiddharth Bhat 1587a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1588a90be207SSiddharth Bhat 158967726b32STobias Grosser Instruction *Param = 159067726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 159167726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 1592d8b94bcaSTobias Grosser EntryBlock->getTerminator()); 1593d8b94bcaSTobias Grosser Builder.CreateStore(Val, Param); 1594a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1595d8b94bcaSTobias Grosser Index++; 1596d8b94bcaSTobias Grosser } 1597d8b94bcaSTobias Grosser 159857693272STobias Grosser for (auto Val : SubtreeValues) { 1599a90be207SSiddharth Bhat ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1600a90be207SSiddharth Bhat 160167726b32STobias Grosser Instruction *Param = 160267726b32STobias Grosser new AllocaInst(Val->getType(), AddressSpace, 160367726b32STobias Grosser Launch + "_param_" + std::to_string(Index), 160457693272STobias Grosser EntryBlock->getTerminator()); 160557693272STobias Grosser Builder.CreateStore(Val, Param); 1606a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 1607a90be207SSiddharth Bhat Index++; 1608a90be207SSiddharth Bhat } 1609a90be207SSiddharth Bhat 1610a90be207SSiddharth Bhat for (int i = 0; i < NumArgs; i++) { 1611a90be207SSiddharth Bhat Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1612a90be207SSiddharth Bhat Instruction *Param = 1613a90be207SSiddharth Bhat new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1614a90be207SSiddharth Bhat Launch + "_param_size_" + std::to_string(i), 1615a90be207SSiddharth Bhat EntryBlock->getTerminator()); 1616a90be207SSiddharth Bhat Builder.CreateStore(Val, Param); 1617a90be207SSiddharth Bhat insertStoreParameter(Parameters, Param, Index); 161857693272STobias Grosser Index++; 161957693272STobias Grosser } 162057693272STobias Grosser 162179a947c2STobias Grosser auto Location = EntryBlock->getTerminator(); 162279a947c2STobias Grosser return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 162379a947c2STobias Grosser Launch + "_params_i8ptr", Location); 162479a947c2STobias Grosser } 162579a947c2STobias Grosser 1626f291c8d5SSiddharth Bhat void GPUNodeBuilder::setupKernelSubtreeFunctions( 1627f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions) { 1628f291c8d5SSiddharth Bhat for (auto Fn : SubtreeFunctions) { 1629f291c8d5SSiddharth Bhat const std::string ClonedFnName = Fn->getName(); 1630f291c8d5SSiddharth Bhat Function *Clone = GPUModule->getFunction(ClonedFnName); 1631f291c8d5SSiddharth Bhat if (!Clone) 1632f291c8d5SSiddharth Bhat Clone = 1633f291c8d5SSiddharth Bhat Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1634f291c8d5SSiddharth Bhat ClonedFnName, GPUModule.get()); 1635f291c8d5SSiddharth Bhat assert(Clone && "Expected cloned function to be initialized."); 1636f291c8d5SSiddharth Bhat assert(ValueMap.find(Fn) == ValueMap.end() && 1637f291c8d5SSiddharth Bhat "Fn already present in ValueMap"); 1638f291c8d5SSiddharth Bhat ValueMap[Fn] = Clone; 1639f291c8d5SSiddharth Bhat } 1640f291c8d5SSiddharth Bhat } 164132837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 164232837fe3STobias Grosser isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 164332837fe3STobias Grosser ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 164432837fe3STobias Grosser isl_id_free(Id); 164532837fe3STobias Grosser isl_ast_node_free(KernelStmt); 164632837fe3STobias Grosser 1647bc653f20STobias Grosser if (Kernel->n_grid > 1) 1648bc653f20STobias Grosser DeepestParallel = 1649bc653f20STobias Grosser std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1650bc653f20STobias Grosser else 1651bc653f20STobias Grosser DeepestSequential = 1652bc653f20STobias Grosser std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1653bc653f20STobias Grosser 1654c1c6a2a6STobias Grosser Value *BlockDimX, *BlockDimY, *BlockDimZ; 1655c1c6a2a6STobias Grosser std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1656c1c6a2a6STobias Grosser 1657f291c8d5SSiddharth Bhat SetVector<Value *> SubtreeValues; 1658f291c8d5SSiddharth Bhat SetVector<Function *> SubtreeFunctions; 1659f291c8d5SSiddharth Bhat std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1660edb885cbSTobias Grosser 166132837fe3STobias Grosser assert(Kernel->tree && "Device AST of kernel node is empty"); 166232837fe3STobias Grosser 166332837fe3STobias Grosser Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1664472f9654STobias Grosser IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1665edb885cbSTobias Grosser ValueMapT HostValueMap = ValueMap; 1666587f1f57STobias Grosser BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1667b06ff457STobias Grosser ScalarMap.clear(); 166832837fe3STobias Grosser 1669edb885cbSTobias Grosser SetVector<const Loop *> Loops; 1670edb885cbSTobias Grosser 1671edb885cbSTobias Grosser // Create for all loops we depend on values that contain the current loop 1672edb885cbSTobias Grosser // iteration. These values are necessary to generate code for SCEVs that 1673edb885cbSTobias Grosser // depend on such loops. As a result we need to pass them to the subfunction. 1674edb885cbSTobias Grosser for (const Loop *L : Loops) { 1675edb885cbSTobias Grosser const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1676edb885cbSTobias Grosser SE.getUnknown(Builder.getInt64(1)), 1677edb885cbSTobias Grosser L, SCEV::FlagAnyWrap); 1678edb885cbSTobias Grosser Value *V = generateSCEV(OuterLIV); 1679edb885cbSTobias Grosser OutsideLoopIterations[L] = SE.getUnknown(V); 1680edb885cbSTobias Grosser SubtreeValues.insert(V); 1681edb885cbSTobias Grosser } 1682edb885cbSTobias Grosser 1683f291c8d5SSiddharth Bhat createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1684f291c8d5SSiddharth Bhat setupKernelSubtreeFunctions(SubtreeFunctions); 168532837fe3STobias Grosser 168659ab0705STobias Grosser create(isl_ast_node_copy(Kernel->tree)); 168759ab0705STobias Grosser 168851dfc275STobias Grosser finalizeKernelArguments(Kernel); 168974dc3cb4STobias Grosser Function *F = Builder.GetInsertBlock()->getParent(); 16902f3073b5SPhilipp Schaad if (Arch == GPUArch::NVPTX64) 1691c1c6a2a6STobias Grosser addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 169274dc3cb4STobias Grosser clearDominators(F); 169374dc3cb4STobias Grosser clearScalarEvolution(F); 169474dc3cb4STobias Grosser clearLoops(F); 169574dc3cb4STobias Grosser 1696472f9654STobias Grosser IDToValue = HostIDs; 169732837fe3STobias Grosser 1698b06ff457STobias Grosser ValueMap = std::move(HostValueMap); 1699b06ff457STobias Grosser ScalarMap = std::move(HostScalarMap); 1700edb885cbSTobias Grosser EscapeMap.clear(); 1701edb885cbSTobias Grosser IDToSAI.clear(); 170274dc3cb4STobias Grosser Annotator.resetAlternativeAliasBases(); 170374dc3cb4STobias Grosser for (auto &BasePtr : LocalArrays) 17044d5a9172STobias Grosser S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 170574dc3cb4STobias Grosser LocalArrays.clear(); 1706edb885cbSTobias Grosser 170751dfc275STobias Grosser std::string ASMString = finalizeKernelFunction(); 170851dfc275STobias Grosser Builder.SetInsertPoint(&HostInsertPoint); 170957693272STobias Grosser Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 171079a947c2STobias Grosser 171179f13b9aSSingapuram Sanjay Srivallabh std::string Name = getKernelFuncName(Kernel->id); 171257793596STobias Grosser Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 171357793596STobias Grosser Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 171457793596STobias Grosser Value *GPUKernel = createCallGetKernel(KernelString, NameString); 171579a947c2STobias Grosser 171679a947c2STobias Grosser Value *GridDimX, *GridDimY; 171779a947c2STobias Grosser std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 171879a947c2STobias Grosser 171979a947c2STobias Grosser createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 172079a947c2STobias Grosser BlockDimZ, Parameters); 172157793596STobias Grosser createCallFreeKernel(GPUKernel); 1722b513b491STobias Grosser 1723b513b491STobias Grosser for (auto Id : KernelIds) 1724b513b491STobias Grosser isl_id_free(Id); 1725b513b491STobias Grosser 1726b513b491STobias Grosser KernelIds.clear(); 172732837fe3STobias Grosser } 172832837fe3STobias Grosser 172932837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend. 173032837fe3STobias Grosser /// 173132837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture? 173232837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) { 1733d277fedaSSiddharth Bhat std::string Ret = ""; 173432837fe3STobias Grosser 1735d277fedaSSiddharth Bhat if (!is64Bit) { 1736d277fedaSSiddharth Bhat Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1737d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1738d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1739d277fedaSSiddharth Bhat } else { 1740d277fedaSSiddharth Bhat Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1741d277fedaSSiddharth Bhat "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1742d277fedaSSiddharth Bhat "64-v128:128:128-n16:32:64"; 1743d277fedaSSiddharth Bhat } 174432837fe3STobias Grosser 174532837fe3STobias Grosser return Ret; 174632837fe3STobias Grosser } 174732837fe3STobias Grosser 17482f3073b5SPhilipp Schaad /// Compute the DataLayout string for a SPIR kernel. 17492f3073b5SPhilipp Schaad /// 17502f3073b5SPhilipp Schaad /// @param is64Bit Are we looking for a 64 bit architecture? 17512f3073b5SPhilipp Schaad static std::string computeSPIRDataLayout(bool is64Bit) { 17522f3073b5SPhilipp Schaad std::string Ret = ""; 17532f3073b5SPhilipp Schaad 17542f3073b5SPhilipp Schaad if (!is64Bit) { 17552f3073b5SPhilipp Schaad Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 17562f3073b5SPhilipp Schaad "64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 17572f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 17582f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 17592f3073b5SPhilipp Schaad } else { 17602f3073b5SPhilipp Schaad Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 17612f3073b5SPhilipp Schaad "64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 17622f3073b5SPhilipp Schaad "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 17632f3073b5SPhilipp Schaad "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 17642f3073b5SPhilipp Schaad } 17652f3073b5SPhilipp Schaad 17662f3073b5SPhilipp Schaad return Ret; 17672f3073b5SPhilipp Schaad } 17682f3073b5SPhilipp Schaad 1769edb885cbSTobias Grosser Function * 1770edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1771edb885cbSTobias Grosser SetVector<Value *> &SubtreeValues) { 177232837fe3STobias Grosser std::vector<Type *> Args; 177379f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 177432837fe3STobias Grosser 17752f3073b5SPhilipp Schaad std::vector<Metadata *> MemoryType; 17762f3073b5SPhilipp Schaad 177732837fe3STobias Grosser for (long i = 0; i < Prog->n_array; i++) { 177832837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 177932837fe3STobias Grosser continue; 178032837fe3STobias Grosser 1781fe74a7a1STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1782fe74a7a1STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1783fe74a7a1STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1784fe74a7a1STobias Grosser Args.push_back(SAI->getElementType()); 17852f3073b5SPhilipp Schaad MemoryType.push_back( 17862f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1787fe74a7a1STobias Grosser } else { 1788d277fedaSSiddharth Bhat static const int UseGlobalMemory = 1; 1789d277fedaSSiddharth Bhat Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 17902f3073b5SPhilipp Schaad MemoryType.push_back( 17912f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 179232837fe3STobias Grosser } 1793fe74a7a1STobias Grosser } 179432837fe3STobias Grosser 1795f6044bd0STobias Grosser int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1796f6044bd0STobias Grosser 17972f3073b5SPhilipp Schaad for (long i = 0; i < NumHostIters; i++) { 1798f6044bd0STobias Grosser Args.push_back(Builder.getInt64Ty()); 17992f3073b5SPhilipp Schaad MemoryType.push_back( 18002f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 18012f3073b5SPhilipp Schaad } 1802f6044bd0STobias Grosser 1803c84a1995STobias Grosser int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1804c84a1995STobias Grosser 1805cf66ef26STobias Grosser for (long i = 0; i < NumVars; i++) { 1806cf66ef26STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1807cf66ef26STobias Grosser Value *Val = IDToValue[Id]; 1808cf66ef26STobias Grosser isl_id_free(Id); 1809cf66ef26STobias Grosser Args.push_back(Val->getType()); 18102f3073b5SPhilipp Schaad MemoryType.push_back( 18112f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1812cf66ef26STobias Grosser } 1813c84a1995STobias Grosser 18142f3073b5SPhilipp Schaad for (auto *V : SubtreeValues) { 1815edb885cbSTobias Grosser Args.push_back(V->getType()); 18162f3073b5SPhilipp Schaad MemoryType.push_back( 18172f3073b5SPhilipp Schaad ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 18182f3073b5SPhilipp Schaad } 1819edb885cbSTobias Grosser 182032837fe3STobias Grosser auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 182132837fe3STobias Grosser auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 182232837fe3STobias Grosser GPUModule.get()); 182317f01968SSiddharth Bhat 18242f3073b5SPhilipp Schaad std::vector<Metadata *> EmptyStrings; 18252f3073b5SPhilipp Schaad 18262f3073b5SPhilipp Schaad for (unsigned int i = 0; i < MemoryType.size(); i++) { 18272f3073b5SPhilipp Schaad EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 18282f3073b5SPhilipp Schaad } 18292f3073b5SPhilipp Schaad 18302f3073b5SPhilipp Schaad if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 18312f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_addr_space", 18322f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), MemoryType)); 18332f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_name", 18342f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 18352f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_access_qual", 18362f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 18372f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type", 18382f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 18392f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_type_qual", 18402f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 18412f3073b5SPhilipp Schaad FN->setMetadata("kernel_arg_base_type", 18422f3073b5SPhilipp Schaad MDNode::get(FN->getContext(), EmptyStrings)); 18432f3073b5SPhilipp Schaad } 18442f3073b5SPhilipp Schaad 184517f01968SSiddharth Bhat switch (Arch) { 184617f01968SSiddharth Bhat case GPUArch::NVPTX64: 184732837fe3STobias Grosser FN->setCallingConv(CallingConv::PTX_Kernel); 184817f01968SSiddharth Bhat break; 18492f3073b5SPhilipp Schaad case GPUArch::SPIR32: 18502f3073b5SPhilipp Schaad case GPUArch::SPIR64: 18512f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_KERNEL); 18522f3073b5SPhilipp Schaad break; 185317f01968SSiddharth Bhat } 185432837fe3STobias Grosser 185532837fe3STobias Grosser auto Arg = FN->arg_begin(); 185632837fe3STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 185732837fe3STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 185832837fe3STobias Grosser continue; 185932837fe3STobias Grosser 1860edb885cbSTobias Grosser Arg->setName(Kernel->array[i].array->name); 1861edb885cbSTobias Grosser 1862edb885cbSTobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1863edb885cbSTobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1864edb885cbSTobias Grosser Type *EleTy = SAI->getElementType(); 1865edb885cbSTobias Grosser Value *Val = &*Arg; 1866edb885cbSTobias Grosser SmallVector<const SCEV *, 4> Sizes; 1867edb885cbSTobias Grosser isl_ast_build *Build = 1868edb885cbSTobias Grosser isl_ast_build_from_context(isl_set_copy(Prog->context)); 1869f5aff704SRoman Gareev Sizes.push_back(nullptr); 1870edb885cbSTobias Grosser for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1871edb885cbSTobias Grosser isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 18729e3db2b7SSiddharth Bhat Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1873edb885cbSTobias Grosser auto V = ExprBuilder.create(DimSize); 1874edb885cbSTobias Grosser Sizes.push_back(SE.getSCEV(V)); 1875edb885cbSTobias Grosser } 1876edb885cbSTobias Grosser const ScopArrayInfo *SAIRep = 18774d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 187874dc3cb4STobias Grosser LocalArrays.push_back(Val); 1879edb885cbSTobias Grosser 1880edb885cbSTobias Grosser isl_ast_build_free(Build); 1881b513b491STobias Grosser KernelIds.push_back(Id); 1882edb885cbSTobias Grosser IDToSAI[Id] = SAIRep; 188332837fe3STobias Grosser Arg++; 188432837fe3STobias Grosser } 188532837fe3STobias Grosser 1886f6044bd0STobias Grosser for (long i = 0; i < NumHostIters; i++) { 1887f6044bd0STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1888f6044bd0STobias Grosser Arg->setName(isl_id_get_name(Id)); 1889f6044bd0STobias Grosser IDToValue[Id] = &*Arg; 1890f6044bd0STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1891f6044bd0STobias Grosser Arg++; 1892f6044bd0STobias Grosser } 1893f6044bd0STobias Grosser 1894c84a1995STobias Grosser for (long i = 0; i < NumVars; i++) { 1895c84a1995STobias Grosser isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1896c84a1995STobias Grosser Arg->setName(isl_id_get_name(Id)); 189712453403STobias Grosser Value *Val = IDToValue[Id]; 189812453403STobias Grosser ValueMap[Val] = &*Arg; 1899c84a1995STobias Grosser IDToValue[Id] = &*Arg; 1900c84a1995STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1901c84a1995STobias Grosser Arg++; 1902c84a1995STobias Grosser } 1903c84a1995STobias Grosser 1904edb885cbSTobias Grosser for (auto *V : SubtreeValues) { 1905edb885cbSTobias Grosser Arg->setName(V->getName()); 1906edb885cbSTobias Grosser ValueMap[V] = &*Arg; 1907edb885cbSTobias Grosser Arg++; 1908edb885cbSTobias Grosser } 1909edb885cbSTobias Grosser 191032837fe3STobias Grosser return FN; 191132837fe3STobias Grosser } 191232837fe3STobias Grosser 1913472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 191417f01968SSiddharth Bhat Intrinsic::ID IntrinsicsBID[2]; 191517f01968SSiddharth Bhat Intrinsic::ID IntrinsicsTID[3]; 1916472f9654STobias Grosser 191717f01968SSiddharth Bhat switch (Arch) { 19182f3073b5SPhilipp Schaad case GPUArch::SPIR64: 19192f3073b5SPhilipp Schaad case GPUArch::SPIR32: 19202f3073b5SPhilipp Schaad llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 192117f01968SSiddharth Bhat case GPUArch::NVPTX64: 192217f01968SSiddharth Bhat IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 192317f01968SSiddharth Bhat IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 192417f01968SSiddharth Bhat 192517f01968SSiddharth Bhat IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 192617f01968SSiddharth Bhat IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 192717f01968SSiddharth Bhat IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 192817f01968SSiddharth Bhat break; 192917f01968SSiddharth Bhat } 1930472f9654STobias Grosser 1931472f9654STobias Grosser auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1932472f9654STobias Grosser std::string Name = isl_id_get_name(Id); 1933472f9654STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1934472f9654STobias Grosser Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1935472f9654STobias Grosser Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1936472f9654STobias Grosser Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1937472f9654STobias Grosser IDToValue[Id] = Val; 1938472f9654STobias Grosser KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1939472f9654STobias Grosser }; 1940472f9654STobias Grosser 1941472f9654STobias Grosser for (int i = 0; i < Kernel->n_grid; ++i) { 1942472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1943472f9654STobias Grosser addId(Id, IntrinsicsBID[i]); 1944472f9654STobias Grosser } 1945472f9654STobias Grosser 1946472f9654STobias Grosser for (int i = 0; i < Kernel->n_block; ++i) { 1947472f9654STobias Grosser isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1948472f9654STobias Grosser addId(Id, IntrinsicsTID[i]); 1949472f9654STobias Grosser } 1950472f9654STobias Grosser } 1951472f9654STobias Grosser 19522f3073b5SPhilipp Schaad void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 19532f3073b5SPhilipp Schaad const char *GroupName[3] = {"__gen_ocl_get_group_id0", 19542f3073b5SPhilipp Schaad "__gen_ocl_get_group_id1", 19552f3073b5SPhilipp Schaad "__gen_ocl_get_group_id2"}; 19562f3073b5SPhilipp Schaad 19572f3073b5SPhilipp Schaad const char *LocalName[3] = {"__gen_ocl_get_local_id0", 19582f3073b5SPhilipp Schaad "__gen_ocl_get_local_id1", 19592f3073b5SPhilipp Schaad "__gen_ocl_get_local_id2"}; 19602f3073b5SPhilipp Schaad 19612f3073b5SPhilipp Schaad auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 19622f3073b5SPhilipp Schaad Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 19632f3073b5SPhilipp Schaad Function *FN = M->getFunction(Name); 19642f3073b5SPhilipp Schaad 19652f3073b5SPhilipp Schaad // If FN is not available, declare it. 19662f3073b5SPhilipp Schaad if (!FN) { 19672f3073b5SPhilipp Schaad GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 19682f3073b5SPhilipp Schaad std::vector<Type *> Args; 19692f3073b5SPhilipp Schaad FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 19702f3073b5SPhilipp Schaad FN = Function::Create(Ty, Linkage, Name, M); 19712f3073b5SPhilipp Schaad FN->setCallingConv(CallingConv::SPIR_FUNC); 19722f3073b5SPhilipp Schaad } 19732f3073b5SPhilipp Schaad 19742f3073b5SPhilipp Schaad Value *Val = Builder.CreateCall(FN, {}); 19752f3073b5SPhilipp Schaad Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 19762f3073b5SPhilipp Schaad IDToValue[Id] = Val; 19772f3073b5SPhilipp Schaad KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 19782f3073b5SPhilipp Schaad }; 19792f3073b5SPhilipp Schaad 19802f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_grid; ++i) 19812f3073b5SPhilipp Schaad createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 19822f3073b5SPhilipp Schaad 19832f3073b5SPhilipp Schaad for (int i = 0; i < Kernel->n_block; ++i) 19842f3073b5SPhilipp Schaad createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 19852f3073b5SPhilipp Schaad } 19862f3073b5SPhilipp Schaad 198700bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 198800bb5a99STobias Grosser auto Arg = FN->arg_begin(); 198900bb5a99STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 199000bb5a99STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 199100bb5a99STobias Grosser continue; 199200bb5a99STobias Grosser 199300bb5a99STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 199400bb5a99STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 199500bb5a99STobias Grosser isl_id_free(Id); 199600bb5a99STobias Grosser 199700bb5a99STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 199800bb5a99STobias Grosser Arg++; 199900bb5a99STobias Grosser continue; 200000bb5a99STobias Grosser } 200100bb5a99STobias Grosser 2002fe74a7a1STobias Grosser Value *Val = &*Arg; 2003fe74a7a1STobias Grosser 2004fe74a7a1STobias Grosser if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 200500bb5a99STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 2006fe74a7a1STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2007fe74a7a1STobias Grosser Val = Builder.CreateLoad(TypedArgPtr); 2008fe74a7a1STobias Grosser } 2009fe74a7a1STobias Grosser 2010fe74a7a1STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 201100bb5a99STobias Grosser Builder.CreateStore(Val, Alloca); 201200bb5a99STobias Grosser 201300bb5a99STobias Grosser Arg++; 201400bb5a99STobias Grosser } 201500bb5a99STobias Grosser } 201600bb5a99STobias Grosser 201751dfc275STobias Grosser void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 201851dfc275STobias Grosser auto *FN = Builder.GetInsertBlock()->getParent(); 201951dfc275STobias Grosser auto Arg = FN->arg_begin(); 202051dfc275STobias Grosser 202151dfc275STobias Grosser bool StoredScalar = false; 202251dfc275STobias Grosser for (long i = 0; i < Kernel->n_array; i++) { 202351dfc275STobias Grosser if (!ppcg_kernel_requires_array_argument(Kernel, i)) 202451dfc275STobias Grosser continue; 202551dfc275STobias Grosser 202651dfc275STobias Grosser isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 202751dfc275STobias Grosser const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 202851dfc275STobias Grosser isl_id_free(Id); 202951dfc275STobias Grosser 203051dfc275STobias Grosser if (SAI->getNumberOfDimensions() > 0) { 203151dfc275STobias Grosser Arg++; 203251dfc275STobias Grosser continue; 203351dfc275STobias Grosser } 203451dfc275STobias Grosser 203551dfc275STobias Grosser if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 203651dfc275STobias Grosser Arg++; 203751dfc275STobias Grosser continue; 203851dfc275STobias Grosser } 203951dfc275STobias Grosser 204051dfc275STobias Grosser Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 204151dfc275STobias Grosser Value *ArgPtr = &*Arg; 204251dfc275STobias Grosser Type *TypePtr = SAI->getElementType()->getPointerTo(); 204351dfc275STobias Grosser Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 204451dfc275STobias Grosser Value *Val = Builder.CreateLoad(Alloca); 204551dfc275STobias Grosser Builder.CreateStore(Val, TypedArgPtr); 204651dfc275STobias Grosser StoredScalar = true; 204751dfc275STobias Grosser 204851dfc275STobias Grosser Arg++; 204951dfc275STobias Grosser } 205051dfc275STobias Grosser 205151dfc275STobias Grosser if (StoredScalar) 205251dfc275STobias Grosser /// In case more than one thread contains scalar stores, the generated 205351dfc275STobias Grosser /// code might be incorrect, if we only store at the end of the kernel. 205451dfc275STobias Grosser /// To support this case we need to store these scalars back at each 205551dfc275STobias Grosser /// memory store or at least before each kernel barrier. 205651dfc275STobias Grosser if (Kernel->n_block != 0 || Kernel->n_grid != 0) 205751dfc275STobias Grosser BuildSuccessful = 0; 205851dfc275STobias Grosser } 205951dfc275STobias Grosser 2060b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2061b513b491STobias Grosser Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2062b513b491STobias Grosser 2063b513b491STobias Grosser for (int i = 0; i < Kernel->n_var; ++i) { 2064b513b491STobias Grosser struct ppcg_kernel_var &Var = Kernel->var[i]; 2065b513b491STobias Grosser isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2066b513b491STobias Grosser Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 2067b513b491STobias Grosser 2068f919d8b3STobias Grosser Type *ArrayTy = EleTy; 2069b513b491STobias Grosser SmallVector<const SCEV *, 4> Sizes; 2070b513b491STobias Grosser 2071f5aff704SRoman Gareev Sizes.push_back(nullptr); 2072928d7573STobias Grosser for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2073b513b491STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2074f919d8b3STobias Grosser long Bound = isl_val_get_num_si(Val); 2075b513b491STobias Grosser isl_val_free(Val); 2076b513b491STobias Grosser Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2077928d7573STobias Grosser } 2078928d7573STobias Grosser 2079928d7573STobias Grosser for (int j = Var.array->n_index - 1; j >= 0; --j) { 2080928d7573STobias Grosser isl_val *Val = isl_vec_get_element_val(Var.size, j); 2081928d7573STobias Grosser long Bound = isl_val_get_num_si(Val); 2082928d7573STobias Grosser isl_val_free(Val); 2083b513b491STobias Grosser ArrayTy = ArrayType::get(ArrayTy, Bound); 2084b513b491STobias Grosser } 2085b513b491STobias Grosser 2086130ca30fSTobias Grosser const ScopArrayInfo *SAI; 2087130ca30fSTobias Grosser Value *Allocation; 2088130ca30fSTobias Grosser if (Var.type == ppcg_access_shared) { 2089130ca30fSTobias Grosser auto GlobalVar = new GlobalVariable( 2090130ca30fSTobias Grosser *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2091130ca30fSTobias Grosser nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2092130ca30fSTobias Grosser GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2093f919d8b3STobias Grosser GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2094f919d8b3STobias Grosser 2095130ca30fSTobias Grosser Allocation = GlobalVar; 2096130ca30fSTobias Grosser } else if (Var.type == ppcg_access_private) { 2097130ca30fSTobias Grosser Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2098130ca30fSTobias Grosser } else { 2099130ca30fSTobias Grosser llvm_unreachable("unknown variable type"); 2100130ca30fSTobias Grosser } 21014d5a9172STobias Grosser SAI = 21024d5a9172STobias Grosser S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2103b513b491STobias Grosser Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2104130ca30fSTobias Grosser IDToValue[Id] = Allocation; 2105130ca30fSTobias Grosser LocalArrays.push_back(Allocation); 2106b513b491STobias Grosser KernelIds.push_back(Id); 2107b513b491STobias Grosser IDToSAI[Id] = SAI; 2108b513b491STobias Grosser } 2109b513b491STobias Grosser } 2110b513b491STobias Grosser 2111f291c8d5SSiddharth Bhat void GPUNodeBuilder::createKernelFunction( 2112f291c8d5SSiddharth Bhat ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2113f291c8d5SSiddharth Bhat SetVector<Function *> &SubtreeFunctions) { 211479f13b9aSSingapuram Sanjay Srivallabh std::string Identifier = getKernelFuncName(Kernel->id); 211532837fe3STobias Grosser GPUModule.reset(new Module(Identifier, Builder.getContext())); 211617f01968SSiddharth Bhat 211717f01968SSiddharth Bhat switch (Arch) { 211817f01968SSiddharth Bhat case GPUArch::NVPTX64: 211917f01968SSiddharth Bhat if (Runtime == GPURuntime::CUDA) 212032837fe3STobias Grosser GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 212117f01968SSiddharth Bhat else if (Runtime == GPURuntime::OpenCL) 212217f01968SSiddharth Bhat GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 212332837fe3STobias Grosser GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 212417f01968SSiddharth Bhat break; 21252f3073b5SPhilipp Schaad case GPUArch::SPIR32: 21262f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 21272f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 21282f3073b5SPhilipp Schaad break; 21292f3073b5SPhilipp Schaad case GPUArch::SPIR64: 21302f3073b5SPhilipp Schaad GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 21312f3073b5SPhilipp Schaad GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 21322f3073b5SPhilipp Schaad break; 213317f01968SSiddharth Bhat } 213432837fe3STobias Grosser 2135edb885cbSTobias Grosser Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 213632837fe3STobias Grosser 213759ab0705STobias Grosser BasicBlock *PrevBlock = Builder.GetInsertBlock(); 213832837fe3STobias Grosser auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 213932837fe3STobias Grosser 214059ab0705STobias Grosser DT.addNewBlock(EntryBlock, PrevBlock); 214159ab0705STobias Grosser 214232837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock); 214332837fe3STobias Grosser Builder.CreateRetVoid(); 214432837fe3STobias Grosser Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2145472f9654STobias Grosser 2146629109b6STobias Grosser ScopDetection::markFunctionAsInvalid(FN); 2147629109b6STobias Grosser 214800bb5a99STobias Grosser prepareKernelArguments(Kernel, FN); 2149b513b491STobias Grosser createKernelVariables(Kernel, FN); 21502f3073b5SPhilipp Schaad 21512f3073b5SPhilipp Schaad switch (Arch) { 21522f3073b5SPhilipp Schaad case GPUArch::NVPTX64: 2153472f9654STobias Grosser insertKernelIntrinsics(Kernel); 21542f3073b5SPhilipp Schaad break; 21552f3073b5SPhilipp Schaad case GPUArch::SPIR32: 21562f3073b5SPhilipp Schaad case GPUArch::SPIR64: 21572f3073b5SPhilipp Schaad insertKernelCallsSPIR(Kernel); 21582f3073b5SPhilipp Schaad break; 21592f3073b5SPhilipp Schaad } 216032837fe3STobias Grosser } 216132837fe3STobias Grosser 216274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() { 216317f01968SSiddharth Bhat llvm::Triple GPUTriple; 216417f01968SSiddharth Bhat 216517f01968SSiddharth Bhat switch (Arch) { 216617f01968SSiddharth Bhat case GPUArch::NVPTX64: 216717f01968SSiddharth Bhat switch (Runtime) { 216817f01968SSiddharth Bhat case GPURuntime::CUDA: 216917f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 217017f01968SSiddharth Bhat break; 217117f01968SSiddharth Bhat case GPURuntime::OpenCL: 217217f01968SSiddharth Bhat GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 217317f01968SSiddharth Bhat break; 217417f01968SSiddharth Bhat } 217517f01968SSiddharth Bhat break; 21762f3073b5SPhilipp Schaad case GPUArch::SPIR64: 21772f3073b5SPhilipp Schaad case GPUArch::SPIR32: 21782f3073b5SPhilipp Schaad std::string SPIRAssembly; 21792f3073b5SPhilipp Schaad raw_string_ostream IROstream(SPIRAssembly); 21802f3073b5SPhilipp Schaad IROstream << *GPUModule; 21812f3073b5SPhilipp Schaad IROstream.flush(); 21822f3073b5SPhilipp Schaad return SPIRAssembly; 218317f01968SSiddharth Bhat } 218417f01968SSiddharth Bhat 218574dc3cb4STobias Grosser std::string ErrMsg; 218674dc3cb4STobias Grosser auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 218774dc3cb4STobias Grosser 218874dc3cb4STobias Grosser if (!GPUTarget) { 218974dc3cb4STobias Grosser errs() << ErrMsg << "\n"; 219074dc3cb4STobias Grosser return ""; 219174dc3cb4STobias Grosser } 219274dc3cb4STobias Grosser 219374dc3cb4STobias Grosser TargetOptions Options; 219474dc3cb4STobias Grosser Options.UnsafeFPMath = FastMath; 219517f01968SSiddharth Bhat 219617f01968SSiddharth Bhat std::string subtarget; 219717f01968SSiddharth Bhat 219817f01968SSiddharth Bhat switch (Arch) { 219917f01968SSiddharth Bhat case GPUArch::NVPTX64: 220017f01968SSiddharth Bhat subtarget = CudaVersion; 220117f01968SSiddharth Bhat break; 22022f3073b5SPhilipp Schaad case GPUArch::SPIR32: 22032f3073b5SPhilipp Schaad case GPUArch::SPIR64: 22042f3073b5SPhilipp Schaad llvm_unreachable("No subtarget for SPIR architecture"); 220517f01968SSiddharth Bhat } 220617f01968SSiddharth Bhat 220717f01968SSiddharth Bhat std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 220817f01968SSiddharth Bhat GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 220974dc3cb4STobias Grosser 221074dc3cb4STobias Grosser SmallString<0> ASMString; 221174dc3cb4STobias Grosser raw_svector_ostream ASMStream(ASMString); 221274dc3cb4STobias Grosser llvm::legacy::PassManager PM; 221374dc3cb4STobias Grosser 221474dc3cb4STobias Grosser PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 221574dc3cb4STobias Grosser 221674dc3cb4STobias Grosser if (TargetM->addPassesToEmitFile( 221774dc3cb4STobias Grosser PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 221874dc3cb4STobias Grosser errs() << "The target does not support generation of this file type!\n"; 221974dc3cb4STobias Grosser return ""; 222074dc3cb4STobias Grosser } 222174dc3cb4STobias Grosser 222274dc3cb4STobias Grosser PM.run(*GPUModule); 222374dc3cb4STobias Grosser 222474dc3cb4STobias Grosser return ASMStream.str(); 222574dc3cb4STobias Grosser } 222674dc3cb4STobias Grosser 222757793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() { 222865d7f72fSSiddharth Bhat 22295857b701STobias Grosser if (verifyModule(*GPUModule)) { 223065d7f72fSSiddharth Bhat DEBUG(dbgs() << "verifyModule failed on module:\n"; 223165d7f72fSSiddharth Bhat GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2232a0fb8b23SSiddharth Bhat DEBUG(dbgs() << "verifyModule Error:\n"; 2233a0fb8b23SSiddharth Bhat verifyModule(*GPUModule, &dbgs());); 223465d7f72fSSiddharth Bhat 223565d7f72fSSiddharth Bhat if (FailOnVerifyModuleFailure) 223665d7f72fSSiddharth Bhat llvm_unreachable("VerifyModule failed."); 223765d7f72fSSiddharth Bhat 22385857b701STobias Grosser BuildSuccessful = false; 22395857b701STobias Grosser return ""; 22405857b701STobias Grosser } 224132837fe3STobias Grosser 224232837fe3STobias Grosser if (DumpKernelIR) 224332837fe3STobias Grosser outs() << *GPUModule << "\n"; 224432837fe3STobias Grosser 22452f3073b5SPhilipp Schaad if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 22469a18d559STobias Grosser // Optimize module. 22479a18d559STobias Grosser llvm::legacy::PassManager OptPasses; 22489a18d559STobias Grosser PassManagerBuilder PassBuilder; 22499a18d559STobias Grosser PassBuilder.OptLevel = 3; 22509a18d559STobias Grosser PassBuilder.SizeLevel = 0; 22519a18d559STobias Grosser PassBuilder.populateModulePassManager(OptPasses); 22529a18d559STobias Grosser OptPasses.run(*GPUModule); 22532f3073b5SPhilipp Schaad } 22549a18d559STobias Grosser 225574dc3cb4STobias Grosser std::string Assembly = createKernelASM(); 225674dc3cb4STobias Grosser 225774dc3cb4STobias Grosser if (DumpKernelASM) 225874dc3cb4STobias Grosser outs() << Assembly << "\n"; 225974dc3cb4STobias Grosser 226032837fe3STobias Grosser GPUModule.release(); 2261472f9654STobias Grosser KernelIDs.clear(); 226257793596STobias Grosser 226357793596STobias Grosser return Assembly; 226432837fe3STobias Grosser } 226532837fe3STobias Grosser 22669dfe4e7cSTobias Grosser namespace { 22679dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass { 22689dfe4e7cSTobias Grosser public: 22699dfe4e7cSTobias Grosser static char ID; 22709dfe4e7cSTobias Grosser 227117f01968SSiddharth Bhat GPURuntime Runtime = GPURuntime::CUDA; 227217f01968SSiddharth Bhat 227317f01968SSiddharth Bhat GPUArch Architecture = GPUArch::NVPTX64; 227417f01968SSiddharth Bhat 2275e938517eSTobias Grosser /// The scop that is currently processed. 2276e938517eSTobias Grosser Scop *S; 2277e938517eSTobias Grosser 227838fc0aedSTobias Grosser LoopInfo *LI; 227938fc0aedSTobias Grosser DominatorTree *DT; 228038fc0aedSTobias Grosser ScalarEvolution *SE; 228138fc0aedSTobias Grosser const DataLayout *DL; 228238fc0aedSTobias Grosser RegionInfo *RI; 228338fc0aedSTobias Grosser 22849dfe4e7cSTobias Grosser PPCGCodeGeneration() : ScopPass(ID) {} 22859dfe4e7cSTobias Grosser 2286e938517eSTobias Grosser /// Construct compilation options for PPCG. 2287e938517eSTobias Grosser /// 2288e938517eSTobias Grosser /// @returns The compilation options. 2289e938517eSTobias Grosser ppcg_options *createPPCGOptions() { 2290e938517eSTobias Grosser auto DebugOptions = 2291e938517eSTobias Grosser (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2292e938517eSTobias Grosser auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2293e938517eSTobias Grosser 2294e938517eSTobias Grosser DebugOptions->dump_schedule_constraints = false; 2295e938517eSTobias Grosser DebugOptions->dump_schedule = false; 2296e938517eSTobias Grosser DebugOptions->dump_final_schedule = false; 2297e938517eSTobias Grosser DebugOptions->dump_sizes = false; 22988950ceadSTobias Grosser DebugOptions->verbose = false; 2299e938517eSTobias Grosser 2300e938517eSTobias Grosser Options->debug = DebugOptions; 2301e938517eSTobias Grosser 23029e3db2b7SSiddharth Bhat Options->group_chains = false; 2303e938517eSTobias Grosser Options->reschedule = true; 2304e938517eSTobias Grosser Options->scale_tile_loops = false; 2305e938517eSTobias Grosser Options->wrap = false; 2306e938517eSTobias Grosser 2307e938517eSTobias Grosser Options->non_negative_parameters = false; 2308e938517eSTobias Grosser Options->ctx = nullptr; 2309e938517eSTobias Grosser Options->sizes = nullptr; 2310e938517eSTobias Grosser 23119e3db2b7SSiddharth Bhat Options->tile = true; 23124eaedde5STobias Grosser Options->tile_size = 32; 23134eaedde5STobias Grosser 23149e3db2b7SSiddharth Bhat Options->isolate_full_tiles = false; 23159e3db2b7SSiddharth Bhat 2316130ca30fSTobias Grosser Options->use_private_memory = PrivateMemory; 2317b513b491STobias Grosser Options->use_shared_memory = SharedMemory; 2318b513b491STobias Grosser Options->max_shared_memory = 48 * 1024; 2319e938517eSTobias Grosser 2320e938517eSTobias Grosser Options->target = PPCG_TARGET_CUDA; 2321e938517eSTobias Grosser Options->openmp = false; 2322e938517eSTobias Grosser Options->linearize_device_arrays = true; 23239e3db2b7SSiddharth Bhat Options->allow_gnu_extensions = false; 2324e938517eSTobias Grosser 23259e3db2b7SSiddharth Bhat Options->unroll_copy_shared = false; 23269e3db2b7SSiddharth Bhat Options->unroll_gpu_tile = false; 23279e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 23289e3db2b7SSiddharth Bhat 23299e3db2b7SSiddharth Bhat Options->live_range_reordering = true; 23309e3db2b7SSiddharth Bhat Options->hybrid = false; 2331e938517eSTobias Grosser Options->opencl_compiler_options = nullptr; 2332e938517eSTobias Grosser Options->opencl_use_gpu = false; 2333e938517eSTobias Grosser Options->opencl_n_include_file = 0; 2334e938517eSTobias Grosser Options->opencl_include_files = nullptr; 2335e938517eSTobias Grosser Options->opencl_print_kernel_types = false; 2336e938517eSTobias Grosser Options->opencl_embed_kernel_code = false; 2337e938517eSTobias Grosser 2338e938517eSTobias Grosser Options->save_schedule_file = nullptr; 2339e938517eSTobias Grosser Options->load_schedule_file = nullptr; 2340e938517eSTobias Grosser 2341e938517eSTobias Grosser return Options; 2342e938517eSTobias Grosser } 2343e938517eSTobias Grosser 2344f384594dSTobias Grosser /// Get a tagged access relation containing all accesses of type @p AccessTy. 2345f384594dSTobias Grosser /// 2346f384594dSTobias Grosser /// Instead of a normal access of the form: 2347f384594dSTobias Grosser /// 2348f384594dSTobias Grosser /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2349f384594dSTobias Grosser /// 2350f384594dSTobias Grosser /// a tagged access has the form 2351f384594dSTobias Grosser /// 2352f384594dSTobias Grosser /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2353f384594dSTobias Grosser /// 2354f384594dSTobias Grosser /// where 'id' is an additional space that references the memory access that 2355f384594dSTobias Grosser /// triggered the access. 2356f384594dSTobias Grosser /// 2357f384594dSTobias Grosser /// @param AccessTy The type of the memory accesses to collect. 2358f384594dSTobias Grosser /// 2359f384594dSTobias Grosser /// @return The relation describing all tagged memory accesses. 2360f384594dSTobias Grosser isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2361f384594dSTobias Grosser isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2362f384594dSTobias Grosser 2363f384594dSTobias Grosser for (auto &Stmt : *S) 2364f384594dSTobias Grosser for (auto &Acc : Stmt) 2365f384594dSTobias Grosser if (Acc->getType() == AccessTy) { 2366f384594dSTobias Grosser isl_map *Relation = Acc->getAccessRelation(); 2367f384594dSTobias Grosser Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2368f384594dSTobias Grosser 2369f384594dSTobias Grosser isl_space *Space = isl_map_get_space(Relation); 2370f384594dSTobias Grosser Space = isl_space_range(Space); 2371f384594dSTobias Grosser Space = isl_space_from_range(Space); 23726293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2373f384594dSTobias Grosser isl_map *Universe = isl_map_universe(Space); 2374f384594dSTobias Grosser Relation = isl_map_domain_product(Relation, Universe); 2375f384594dSTobias Grosser Accesses = isl_union_map_add_map(Accesses, Relation); 2376f384594dSTobias Grosser } 2377f384594dSTobias Grosser 2378f384594dSTobias Grosser return Accesses; 2379f384594dSTobias Grosser } 2380f384594dSTobias Grosser 2381f384594dSTobias Grosser /// Get the set of all read accesses, tagged with the access id. 2382f384594dSTobias Grosser /// 2383f384594dSTobias Grosser /// @see getTaggedAccesses 2384f384594dSTobias Grosser isl_union_map *getTaggedReads() { 2385f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::READ); 2386f384594dSTobias Grosser } 2387f384594dSTobias Grosser 2388f384594dSTobias Grosser /// Get the set of all may (and must) accesses, tagged with the access id. 2389f384594dSTobias Grosser /// 2390f384594dSTobias Grosser /// @see getTaggedAccesses 2391f384594dSTobias Grosser isl_union_map *getTaggedMayWrites() { 2392f384594dSTobias Grosser return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2393f384594dSTobias Grosser getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2394f384594dSTobias Grosser } 2395f384594dSTobias Grosser 2396f384594dSTobias Grosser /// Get the set of all must accesses, tagged with the access id. 2397f384594dSTobias Grosser /// 2398f384594dSTobias Grosser /// @see getTaggedAccesses 2399f384594dSTobias Grosser isl_union_map *getTaggedMustWrites() { 2400f384594dSTobias Grosser return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2401f384594dSTobias Grosser } 2402f384594dSTobias Grosser 2403aef5196fSTobias Grosser /// Collect parameter and array names as isl_ids. 2404aef5196fSTobias Grosser /// 2405aef5196fSTobias Grosser /// To reason about the different parameters and arrays used, ppcg requires 2406aef5196fSTobias Grosser /// a list of all isl_ids in use. As PPCG traditionally performs 2407aef5196fSTobias Grosser /// source-to-source compilation each of these isl_ids is mapped to the 2408aef5196fSTobias Grosser /// expression that represents it. As we do not have a corresponding 2409aef5196fSTobias Grosser /// expression in Polly, we just map each id to a 'zero' expression to match 2410aef5196fSTobias Grosser /// the data format that ppcg expects. 2411aef5196fSTobias Grosser /// 2412aef5196fSTobias Grosser /// @returns Retun a map from collected ids to 'zero' ast expressions. 2413aef5196fSTobias Grosser __isl_give isl_id_to_ast_expr *getNames() { 2414aef5196fSTobias Grosser auto *Names = isl_id_to_ast_expr_alloc( 2415bd81a7eeSTobias Grosser S->getIslCtx(), 2416bd81a7eeSTobias Grosser S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2417aef5196fSTobias Grosser auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2418aef5196fSTobias Grosser auto *Space = S->getParamSpace(); 2419aef5196fSTobias Grosser 2420aef5196fSTobias Grosser for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2421aef5196fSTobias Grosser isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2422aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2423aef5196fSTobias Grosser } 2424aef5196fSTobias Grosser 2425aef5196fSTobias Grosser for (auto &Array : S->arrays()) { 2426*77eef90fSTobias Grosser auto Id = Array->getBasePtrId().release(); 2427aef5196fSTobias Grosser Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2428aef5196fSTobias Grosser } 2429aef5196fSTobias Grosser 2430aef5196fSTobias Grosser isl_space_free(Space); 2431aef5196fSTobias Grosser isl_ast_expr_free(Zero); 2432aef5196fSTobias Grosser 2433aef5196fSTobias Grosser return Names; 2434aef5196fSTobias Grosser } 2435aef5196fSTobias Grosser 2436e938517eSTobias Grosser /// Create a new PPCG scop from the current scop. 2437e938517eSTobias Grosser /// 2438f384594dSTobias Grosser /// The PPCG scop is initialized with data from the current polly::Scop. From 2439f384594dSTobias Grosser /// this initial data, the data-dependences in the PPCG scop are initialized. 2440f384594dSTobias Grosser /// We do not use Polly's dependence analysis for now, to ensure we match 2441f384594dSTobias Grosser /// the PPCG default behaviour more closely. 2442e938517eSTobias Grosser /// 2443e938517eSTobias Grosser /// @returns A new ppcg scop. 2444e938517eSTobias Grosser ppcg_scop *createPPCGScop() { 24459e3db2b7SSiddharth Bhat MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 24469e3db2b7SSiddharth Bhat 2447e938517eSTobias Grosser auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2448e938517eSTobias Grosser 2449e938517eSTobias Grosser PPCGScop->options = createPPCGOptions(); 2450a82f2d26SSiddharth Bhat // enable live range reordering 2451a82f2d26SSiddharth Bhat PPCGScop->options->live_range_reordering = 1; 2452e938517eSTobias Grosser 2453e938517eSTobias Grosser PPCGScop->start = 0; 2454e938517eSTobias Grosser PPCGScop->end = 0; 2455e938517eSTobias Grosser 2456f384594dSTobias Grosser PPCGScop->context = S->getContext(); 2457f384594dSTobias Grosser PPCGScop->domain = S->getDomains(); 24589e3db2b7SSiddharth Bhat // TODO: investigate this further. PPCG calls collect_call_domains. 24599e3db2b7SSiddharth Bhat PPCGScop->call = isl_union_set_from_set(S->getContext()); 2460f384594dSTobias Grosser PPCGScop->tagged_reads = getTaggedReads(); 2461f384594dSTobias Grosser PPCGScop->reads = S->getReads(); 2462e938517eSTobias Grosser PPCGScop->live_in = nullptr; 2463f384594dSTobias Grosser PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2464f384594dSTobias Grosser PPCGScop->may_writes = S->getWrites(); 2465f384594dSTobias Grosser PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2466f384594dSTobias Grosser PPCGScop->must_writes = S->getMustWrites(); 2467e938517eSTobias Grosser PPCGScop->live_out = nullptr; 24689e3db2b7SSiddharth Bhat PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 24699e3db2b7SSiddharth Bhat PPCGScop->must_kills = KillsInfo.MustKills.take(); 24709e3db2b7SSiddharth Bhat 2471e938517eSTobias Grosser PPCGScop->tagger = nullptr; 2472a82f2d26SSiddharth Bhat PPCGScop->independence = 2473a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2474e938517eSTobias Grosser PPCGScop->dep_flow = nullptr; 2475e938517eSTobias Grosser PPCGScop->tagged_dep_flow = nullptr; 2476e938517eSTobias Grosser PPCGScop->dep_false = nullptr; 2477e938517eSTobias Grosser PPCGScop->dep_forced = nullptr; 2478e938517eSTobias Grosser PPCGScop->dep_order = nullptr; 2479e938517eSTobias Grosser PPCGScop->tagged_dep_order = nullptr; 2480e938517eSTobias Grosser 2481f384594dSTobias Grosser PPCGScop->schedule = S->getScheduleTree(); 2482a82f2d26SSiddharth Bhat // If we have something non-trivial to kill, add it to the schedule 2483a82f2d26SSiddharth Bhat if (KillsInfo.KillsSchedule.get()) 2484a82f2d26SSiddharth Bhat PPCGScop->schedule = isl_schedule_sequence( 2485a82f2d26SSiddharth Bhat PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2486a82f2d26SSiddharth Bhat 2487a82f2d26SSiddharth Bhat PPCGScop->names = getNames(); 2488e938517eSTobias Grosser PPCGScop->pet = nullptr; 2489e938517eSTobias Grosser 2490f384594dSTobias Grosser compute_tagger(PPCGScop); 2491f384594dSTobias Grosser compute_dependences(PPCGScop); 24929e3db2b7SSiddharth Bhat eliminate_dead_code(PPCGScop); 2493f384594dSTobias Grosser 2494e938517eSTobias Grosser return PPCGScop; 2495e938517eSTobias Grosser } 2496e938517eSTobias Grosser 2497a6d48f59SMichael Kruse /// Collect the array accesses in a statement. 249860f63b49STobias Grosser /// 249960f63b49STobias Grosser /// @param Stmt The statement for which to collect the accesses. 250060f63b49STobias Grosser /// 250160f63b49STobias Grosser /// @returns A list of array accesses. 250260f63b49STobias Grosser gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 250360f63b49STobias Grosser gpu_stmt_access *Accesses = nullptr; 250460f63b49STobias Grosser 250560f63b49STobias Grosser for (MemoryAccess *Acc : Stmt) { 250660f63b49STobias Grosser auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 250760f63b49STobias Grosser Access->read = Acc->isRead(); 250860f63b49STobias Grosser Access->write = Acc->isWrite(); 250960f63b49STobias Grosser Access->access = Acc->getAccessRelation(); 251060f63b49STobias Grosser isl_space *Space = isl_map_get_space(Access->access); 251160f63b49STobias Grosser Space = isl_space_range(Space); 251260f63b49STobias Grosser Space = isl_space_from_range(Space); 25136293ba69STobias Grosser Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 251460f63b49STobias Grosser isl_map *Universe = isl_map_universe(Space); 251560f63b49STobias Grosser Access->tagged_access = 251660f63b49STobias Grosser isl_map_domain_product(Acc->getAccessRelation(), Universe); 2517b513b491STobias Grosser Access->exact_write = !Acc->isMayWrite(); 251860f63b49STobias Grosser Access->ref_id = Acc->getId(); 251960f63b49STobias Grosser Access->next = Accesses; 2520b513b491STobias Grosser Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 252160f63b49STobias Grosser Accesses = Access; 252260f63b49STobias Grosser } 252360f63b49STobias Grosser 252460f63b49STobias Grosser return Accesses; 252560f63b49STobias Grosser } 252660f63b49STobias Grosser 252769b46751STobias Grosser /// Collect the list of GPU statements. 252869b46751STobias Grosser /// 252969b46751STobias Grosser /// Each statement has an id, a pointer to the underlying data structure, 253069b46751STobias Grosser /// as well as a list with all memory accesses. 253169b46751STobias Grosser /// 253269b46751STobias Grosser /// TODO: Initialize the list of memory accesses. 253369b46751STobias Grosser /// 253469b46751STobias Grosser /// @returns A linked-list of statements. 253569b46751STobias Grosser gpu_stmt *getStatements() { 253669b46751STobias Grosser gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 253769b46751STobias Grosser std::distance(S->begin(), S->end())); 253869b46751STobias Grosser 253969b46751STobias Grosser int i = 0; 254069b46751STobias Grosser for (auto &Stmt : *S) { 254169b46751STobias Grosser gpu_stmt *GPUStmt = &Stmts[i]; 254269b46751STobias Grosser 254369b46751STobias Grosser GPUStmt->id = Stmt.getDomainId(); 254469b46751STobias Grosser 254569b46751STobias Grosser // We use the pet stmt pointer to keep track of the Polly statements. 254669b46751STobias Grosser GPUStmt->stmt = (pet_stmt *)&Stmt; 254760f63b49STobias Grosser GPUStmt->accesses = getStmtAccesses(Stmt); 254869b46751STobias Grosser i++; 254969b46751STobias Grosser } 255069b46751STobias Grosser 255169b46751STobias Grosser return Stmts; 255269b46751STobias Grosser } 255369b46751STobias Grosser 255460f63b49STobias Grosser /// Derive the extent of an array. 255560f63b49STobias Grosser /// 2556d58acf86STobias Grosser /// The extent of an array is the set of elements that are within the 2557d58acf86STobias Grosser /// accessed array. For the inner dimensions, the extent constraints are 2558d58acf86STobias Grosser /// 0 and the size of the corresponding array dimension. For the first 2559d58acf86STobias Grosser /// (outermost) dimension, the extent constraints are the minimal and maximal 2560d58acf86STobias Grosser /// subscript value for the first dimension. 256160f63b49STobias Grosser /// 256260f63b49STobias Grosser /// @param Array The array to derive the extent for. 256360f63b49STobias Grosser /// 256460f63b49STobias Grosser /// @returns An isl_set describing the extent of the array. 256560f63b49STobias Grosser __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2566d58acf86STobias Grosser unsigned NumDims = Array->getNumberOfDimensions(); 256760f63b49STobias Grosser isl_union_map *Accesses = S->getAccesses(); 256860f63b49STobias Grosser Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2569d58acf86STobias Grosser Accesses = isl_union_map_detect_equalities(Accesses); 257060f63b49STobias Grosser isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2571d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2572d58acf86STobias Grosser AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2573d58acf86STobias Grosser AccessUSet = isl_union_set_coalesce(AccessUSet); 2574d58acf86STobias Grosser 2575d58acf86STobias Grosser if (isl_union_set_is_empty(AccessUSet)) { 2576d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2577*77eef90fSTobias Grosser return isl_set_empty(Array->getSpace().release()); 2578d58acf86STobias Grosser } 2579d58acf86STobias Grosser 2580d58acf86STobias Grosser if (Array->getNumberOfDimensions() == 0) { 2581d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2582*77eef90fSTobias Grosser return isl_set_universe(Array->getSpace().release()); 2583d58acf86STobias Grosser } 2584d58acf86STobias Grosser 258560f63b49STobias Grosser isl_set *AccessSet = 2586*77eef90fSTobias Grosser isl_union_set_extract_set(AccessUSet, Array->getSpace().release()); 258760f63b49STobias Grosser 2588d58acf86STobias Grosser isl_union_set_free(AccessUSet); 2589*77eef90fSTobias Grosser isl_local_space *LS = 2590*77eef90fSTobias Grosser isl_local_space_from_space(Array->getSpace().release()); 2591d58acf86STobias Grosser 2592d58acf86STobias Grosser isl_pw_aff *Val = 2593d58acf86STobias Grosser isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2594d58acf86STobias Grosser 2595d58acf86STobias Grosser isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2596d58acf86STobias Grosser isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2597d58acf86STobias Grosser OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2598d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2599d58acf86STobias Grosser OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2600d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2601*77eef90fSTobias Grosser OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, 2602*77eef90fSTobias Grosser Array->getBasePtrId().release()); 2603*77eef90fSTobias Grosser OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, 2604*77eef90fSTobias Grosser Array->getBasePtrId().release()); 2605d58acf86STobias Grosser 2606*77eef90fSTobias Grosser isl_set *Extent = isl_set_universe(Array->getSpace().release()); 2607d58acf86STobias Grosser 2608d58acf86STobias Grosser Extent = isl_set_intersect( 2609d58acf86STobias Grosser Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2610d58acf86STobias Grosser Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2611d58acf86STobias Grosser 2612d58acf86STobias Grosser for (unsigned i = 1; i < NumDims; ++i) 2613d58acf86STobias Grosser Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2614d58acf86STobias Grosser 2615b7f68b8cSSiddharth Bhat for (unsigned i = 0; i < NumDims; ++i) { 2616d58acf86STobias Grosser isl_pw_aff *PwAff = 2617*77eef90fSTobias Grosser const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release()); 2618b7f68b8cSSiddharth Bhat 2619b7f68b8cSSiddharth Bhat // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2620b7f68b8cSSiddharth Bhat // Fortran array will we have a legitimate dimension. 2621b7f68b8cSSiddharth Bhat if (!PwAff) { 2622b7f68b8cSSiddharth Bhat assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2623b7f68b8cSSiddharth Bhat continue; 2624b7f68b8cSSiddharth Bhat } 2625b7f68b8cSSiddharth Bhat 2626d58acf86STobias Grosser isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2627*77eef90fSTobias Grosser isl_local_space_from_space(Array->getSpace().release()), isl_dim_set, 2628*77eef90fSTobias Grosser i)); 2629d58acf86STobias Grosser PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2630d58acf86STobias Grosser isl_pw_aff_dim(Val, isl_dim_in)); 2631d58acf86STobias Grosser PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2632d58acf86STobias Grosser isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2633d58acf86STobias Grosser auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2634d58acf86STobias Grosser Extent = isl_set_intersect(Set, Extent); 2635d58acf86STobias Grosser } 2636d58acf86STobias Grosser 2637d58acf86STobias Grosser return Extent; 263860f63b49STobias Grosser } 263960f63b49STobias Grosser 264060f63b49STobias Grosser /// Derive the bounds of an array. 264160f63b49STobias Grosser /// 264260f63b49STobias Grosser /// For the first dimension we derive the bound of the array from the extent 264360f63b49STobias Grosser /// of this dimension. For inner dimensions we obtain their size directly from 264460f63b49STobias Grosser /// ScopArrayInfo. 264560f63b49STobias Grosser /// 264660f63b49STobias Grosser /// @param PPCGArray The array to compute bounds for. 264760f63b49STobias Grosser /// @param Array The polly array from which to take the information. 264860f63b49STobias Grosser void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 26499e3db2b7SSiddharth Bhat isl_pw_aff_list *BoundsList = 26509e3db2b7SSiddharth Bhat isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index); 26519e3db2b7SSiddharth Bhat std::vector<isl::pw_aff> PwAffs; 26529e3db2b7SSiddharth Bhat 26539e3db2b7SSiddharth Bhat isl_space *AlignSpace = S->getParamSpace(); 26549e3db2b7SSiddharth Bhat AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1); 26559e3db2b7SSiddharth Bhat 265660f63b49STobias Grosser if (PPCGArray.n_index > 0) { 265702293ed7STobias Grosser if (isl_set_is_empty(PPCGArray.extent)) { 265802293ed7STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 265902293ed7STobias Grosser isl_local_space *LS = isl_local_space_from_space( 266002293ed7STobias Grosser isl_space_params(isl_set_get_space(Dom))); 266102293ed7STobias Grosser isl_set_free(Dom); 26629e3db2b7SSiddharth Bhat isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 26639e3db2b7SSiddharth Bhat Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace)); 26649e3db2b7SSiddharth Bhat PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero))); 26659e3db2b7SSiddharth Bhat BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero); 266602293ed7STobias Grosser } else { 266760f63b49STobias Grosser isl_set *Dom = isl_set_copy(PPCGArray.extent); 266860f63b49STobias Grosser Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 266960f63b49STobias Grosser isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 267060f63b49STobias Grosser isl_set_free(Dom); 267160f63b49STobias Grosser Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 267202293ed7STobias Grosser isl_local_space *LS = 267302293ed7STobias Grosser isl_local_space_from_space(isl_set_get_space(Dom)); 267460f63b49STobias Grosser isl_aff *One = isl_aff_zero_on_domain(LS); 267560f63b49STobias Grosser One = isl_aff_add_constant_si(One, 1); 267660f63b49STobias Grosser Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 267760f63b49STobias Grosser Bound = isl_pw_aff_gist(Bound, S->getContext()); 26789e3db2b7SSiddharth Bhat Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 26799e3db2b7SSiddharth Bhat PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 26809e3db2b7SSiddharth Bhat BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound); 268160f63b49STobias Grosser } 268202293ed7STobias Grosser } 268360f63b49STobias Grosser 268460f63b49STobias Grosser for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2685*77eef90fSTobias Grosser isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 268660f63b49STobias Grosser auto LS = isl_pw_aff_get_domain_space(Bound); 268760f63b49STobias Grosser auto Aff = isl_multi_aff_zero(LS); 268860f63b49STobias Grosser Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 26899e3db2b7SSiddharth Bhat Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 26909e3db2b7SSiddharth Bhat PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 26919e3db2b7SSiddharth Bhat BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound); 269260f63b49STobias Grosser } 26939e3db2b7SSiddharth Bhat 26949e3db2b7SSiddharth Bhat isl_space_free(AlignSpace); 26959e3db2b7SSiddharth Bhat isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 26969e3db2b7SSiddharth Bhat 26979e3db2b7SSiddharth Bhat assert(BoundsSpace && "Unable to access space of array."); 26989e3db2b7SSiddharth Bhat assert(BoundsList && "Unable to access list of bounds."); 26999e3db2b7SSiddharth Bhat 27009e3db2b7SSiddharth Bhat PPCGArray.bound = 27019e3db2b7SSiddharth Bhat isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 27029e3db2b7SSiddharth Bhat assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 270360f63b49STobias Grosser } 270460f63b49STobias Grosser 270560f63b49STobias Grosser /// Create the arrays for @p PPCGProg. 270660f63b49STobias Grosser /// 270760f63b49STobias Grosser /// @param PPCGProg The program to compute the arrays for. 270860f63b49STobias Grosser void createArrays(gpu_prog *PPCGProg) { 270960f63b49STobias Grosser int i = 0; 2710d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 271160f63b49STobias Grosser std::string TypeName; 271260f63b49STobias Grosser raw_string_ostream OS(TypeName); 271360f63b49STobias Grosser 271460f63b49STobias Grosser OS << *Array->getElementType(); 271560f63b49STobias Grosser TypeName = OS.str(); 271660f63b49STobias Grosser 271760f63b49STobias Grosser gpu_array_info &PPCGArray = PPCGProg->array[i]; 271860f63b49STobias Grosser 2719*77eef90fSTobias Grosser PPCGArray.space = Array->getSpace().release(); 272060f63b49STobias Grosser PPCGArray.type = strdup(TypeName.c_str()); 272160f63b49STobias Grosser PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 272260f63b49STobias Grosser PPCGArray.name = strdup(Array->getName().c_str()); 272360f63b49STobias Grosser PPCGArray.extent = nullptr; 272460f63b49STobias Grosser PPCGArray.n_index = Array->getNumberOfDimensions(); 272560f63b49STobias Grosser PPCGArray.extent = getExtent(Array); 272660f63b49STobias Grosser PPCGArray.n_ref = 0; 272760f63b49STobias Grosser PPCGArray.refs = nullptr; 272860f63b49STobias Grosser PPCGArray.accessed = true; 2729fe74a7a1STobias Grosser PPCGArray.read_only_scalar = 2730fe74a7a1STobias Grosser Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 273160f63b49STobias Grosser PPCGArray.has_compound_element = false; 273260f63b49STobias Grosser PPCGArray.local = false; 273360f63b49STobias Grosser PPCGArray.declare_local = false; 273460f63b49STobias Grosser PPCGArray.global = false; 273560f63b49STobias Grosser PPCGArray.linearize = false; 273660f63b49STobias Grosser PPCGArray.dep_order = nullptr; 273713c78e4dSTobias Grosser PPCGArray.user = Array; 273860f63b49STobias Grosser 27399e3db2b7SSiddharth Bhat PPCGArray.bound = nullptr; 274060f63b49STobias Grosser setArrayBounds(PPCGArray, Array); 27412d010dafSTobias Grosser i++; 2742b9fc860aSTobias Grosser 2743b9fc860aSTobias Grosser collect_references(PPCGProg, &PPCGArray); 274460f63b49STobias Grosser } 274560f63b49STobias Grosser } 274660f63b49STobias Grosser 274760f63b49STobias Grosser /// Create an identity map between the arrays in the scop. 274860f63b49STobias Grosser /// 274960f63b49STobias Grosser /// @returns An identity map between the arrays in the scop. 275060f63b49STobias Grosser isl_union_map *getArrayIdentity() { 275160f63b49STobias Grosser isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 275260f63b49STobias Grosser 2753d7754a12SRoman Gareev for (auto &Array : S->arrays()) { 2754*77eef90fSTobias Grosser isl_space *Space = Array->getSpace().release(); 275560f63b49STobias Grosser Space = isl_space_map_from_set(Space); 275660f63b49STobias Grosser isl_map *Identity = isl_map_identity(Space); 275760f63b49STobias Grosser Maps = isl_union_map_add_map(Maps, Identity); 275860f63b49STobias Grosser } 275960f63b49STobias Grosser 276060f63b49STobias Grosser return Maps; 276160f63b49STobias Grosser } 276260f63b49STobias Grosser 2763e938517eSTobias Grosser /// Create a default-initialized PPCG GPU program. 2764e938517eSTobias Grosser /// 2765a6d48f59SMichael Kruse /// @returns A new gpu program description. 2766e938517eSTobias Grosser gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2767e938517eSTobias Grosser 2768e938517eSTobias Grosser if (!PPCGScop) 2769e938517eSTobias Grosser return nullptr; 2770e938517eSTobias Grosser 2771e938517eSTobias Grosser auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2772e938517eSTobias Grosser 2773e938517eSTobias Grosser PPCGProg->ctx = S->getIslCtx(); 2774e938517eSTobias Grosser PPCGProg->scop = PPCGScop; 2775aef5196fSTobias Grosser PPCGProg->context = isl_set_copy(PPCGScop->context); 277660f63b49STobias Grosser PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 277760f63b49STobias Grosser PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 277860f63b49STobias Grosser PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 277960f63b49STobias Grosser PPCGProg->tagged_must_kill = 278060f63b49STobias Grosser isl_union_map_copy(PPCGScop->tagged_must_kills); 278160f63b49STobias Grosser PPCGProg->to_inner = getArrayIdentity(); 278260f63b49STobias Grosser PPCGProg->to_outer = getArrayIdentity(); 27839e3db2b7SSiddharth Bhat // TODO: verify that this assignment is correct. 2784e938517eSTobias Grosser PPCGProg->any_to_outer = nullptr; 2785a82f2d26SSiddharth Bhat 2786a82f2d26SSiddharth Bhat // this needs to be set when live range reordering is enabled. 2787a82f2d26SSiddharth Bhat // NOTE: I believe that is conservatively correct. I'm not sure 2788a82f2d26SSiddharth Bhat // what the semantics of this is. 2789a82f2d26SSiddharth Bhat // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2790a82f2d26SSiddharth Bhat PPCGProg->array_order = 2791a82f2d26SSiddharth Bhat isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 279269b46751STobias Grosser PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 279369b46751STobias Grosser PPCGProg->stmts = getStatements(); 279460f63b49STobias Grosser PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 279560f63b49STobias Grosser PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 279660f63b49STobias Grosser PPCGProg->n_array); 279760f63b49STobias Grosser 279860f63b49STobias Grosser createArrays(PPCGProg); 2799e938517eSTobias Grosser 2800d58acf86STobias Grosser PPCGProg->may_persist = compute_may_persist(PPCGProg); 2801e938517eSTobias Grosser return PPCGProg; 2802e938517eSTobias Grosser } 2803e938517eSTobias Grosser 280469b46751STobias Grosser struct PrintGPUUserData { 280569b46751STobias Grosser struct cuda_info *CudaInfo; 280669b46751STobias Grosser struct gpu_prog *PPCGProg; 280769b46751STobias Grosser std::vector<ppcg_kernel *> Kernels; 280869b46751STobias Grosser }; 280969b46751STobias Grosser 281069b46751STobias Grosser /// Print a user statement node in the host code. 281169b46751STobias Grosser /// 281269b46751STobias Grosser /// We use ppcg's printing facilities to print the actual statement and 281369b46751STobias Grosser /// additionally build up a list of all kernels that are encountered in the 281469b46751STobias Grosser /// host ast. 281569b46751STobias Grosser /// 281669b46751STobias Grosser /// @param P The printer to print to 281769b46751STobias Grosser /// @param Options The printing options to use 281869b46751STobias Grosser /// @param Node The node to print 281969b46751STobias Grosser /// @param User A user pointer to carry additional data. This pointer is 282069b46751STobias Grosser /// expected to be of type PrintGPUUserData. 282169b46751STobias Grosser /// 282269b46751STobias Grosser /// @returns A printer to which the output has been printed. 282369b46751STobias Grosser static __isl_give isl_printer * 282469b46751STobias Grosser printHostUser(__isl_take isl_printer *P, 282569b46751STobias Grosser __isl_take isl_ast_print_options *Options, 282669b46751STobias Grosser __isl_take isl_ast_node *Node, void *User) { 282769b46751STobias Grosser auto Data = (struct PrintGPUUserData *)User; 282869b46751STobias Grosser auto Id = isl_ast_node_get_annotation(Node); 282969b46751STobias Grosser 283069b46751STobias Grosser if (Id) { 283120251734STobias Grosser bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 283220251734STobias Grosser 283320251734STobias Grosser // If this is a user statement, format it ourselves as ppcg would 283420251734STobias Grosser // otherwise try to call pet functionality that is not available in 283520251734STobias Grosser // Polly. 283620251734STobias Grosser if (IsUser) { 283720251734STobias Grosser P = isl_printer_start_line(P); 283820251734STobias Grosser P = isl_printer_print_ast_node(P, Node); 283920251734STobias Grosser P = isl_printer_end_line(P); 284020251734STobias Grosser isl_id_free(Id); 284120251734STobias Grosser isl_ast_print_options_free(Options); 284220251734STobias Grosser return P; 284320251734STobias Grosser } 284420251734STobias Grosser 284569b46751STobias Grosser auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 284669b46751STobias Grosser isl_id_free(Id); 284769b46751STobias Grosser Data->Kernels.push_back(Kernel); 284869b46751STobias Grosser } 284969b46751STobias Grosser 285069b46751STobias Grosser return print_host_user(P, Options, Node, User); 285169b46751STobias Grosser } 285269b46751STobias Grosser 285369b46751STobias Grosser /// Print C code corresponding to the control flow in @p Kernel. 285469b46751STobias Grosser /// 285569b46751STobias Grosser /// @param Kernel The kernel to print 285669b46751STobias Grosser void printKernel(ppcg_kernel *Kernel) { 285769b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 285869b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 285969b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 286069b46751STobias Grosser P = isl_ast_node_print(Kernel->tree, P, Options); 286169b46751STobias Grosser char *String = isl_printer_get_str(P); 286269b46751STobias Grosser printf("%s\n", String); 286369b46751STobias Grosser free(String); 286469b46751STobias Grosser isl_printer_free(P); 286569b46751STobias Grosser } 286669b46751STobias Grosser 286769b46751STobias Grosser /// Print C code corresponding to the GPU code described by @p Tree. 286869b46751STobias Grosser /// 286969b46751STobias Grosser /// @param Tree An AST describing GPU code 287069b46751STobias Grosser /// @param PPCGProg The PPCG program from which @Tree has been constructed. 287169b46751STobias Grosser void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 287269b46751STobias Grosser auto *P = isl_printer_to_str(S->getIslCtx()); 287369b46751STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C); 287469b46751STobias Grosser 287569b46751STobias Grosser PrintGPUUserData Data; 287669b46751STobias Grosser Data.PPCGProg = PPCGProg; 287769b46751STobias Grosser 287869b46751STobias Grosser auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 287969b46751STobias Grosser Options = 288069b46751STobias Grosser isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 288169b46751STobias Grosser P = isl_ast_node_print(Tree, P, Options); 288269b46751STobias Grosser char *String = isl_printer_get_str(P); 288369b46751STobias Grosser printf("# host\n"); 288469b46751STobias Grosser printf("%s\n", String); 288569b46751STobias Grosser free(String); 288669b46751STobias Grosser isl_printer_free(P); 288769b46751STobias Grosser 288869b46751STobias Grosser for (auto Kernel : Data.Kernels) { 288969b46751STobias Grosser printf("# kernel%d\n", Kernel->id); 289069b46751STobias Grosser printKernel(Kernel); 289169b46751STobias Grosser } 289269b46751STobias Grosser } 289369b46751STobias Grosser 2894f384594dSTobias Grosser // Generate a GPU program using PPCG. 2895f384594dSTobias Grosser // 2896f384594dSTobias Grosser // GPU mapping consists of multiple steps: 2897f384594dSTobias Grosser // 2898f384594dSTobias Grosser // 1) Compute new schedule for the program. 2899f384594dSTobias Grosser // 2) Map schedule to GPU (TODO) 2900f384594dSTobias Grosser // 3) Generate code for new schedule (TODO) 2901f384594dSTobias Grosser // 2902f384594dSTobias Grosser // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2903f384594dSTobias Grosser // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2904f384594dSTobias Grosser // strategy directly from this pass. 2905f384594dSTobias Grosser gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2906f384594dSTobias Grosser 2907f384594dSTobias Grosser auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2908f384594dSTobias Grosser 2909f384594dSTobias Grosser PPCGGen->ctx = S->getIslCtx(); 2910f384594dSTobias Grosser PPCGGen->options = PPCGScop->options; 2911f384594dSTobias Grosser PPCGGen->print = nullptr; 2912f384594dSTobias Grosser PPCGGen->print_user = nullptr; 291360c60025STobias Grosser PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2914f384594dSTobias Grosser PPCGGen->prog = PPCGProg; 2915f384594dSTobias Grosser PPCGGen->tree = nullptr; 2916f384594dSTobias Grosser PPCGGen->types.n = 0; 2917f384594dSTobias Grosser PPCGGen->types.name = nullptr; 2918f384594dSTobias Grosser PPCGGen->sizes = nullptr; 2919f384594dSTobias Grosser PPCGGen->used_sizes = nullptr; 2920f384594dSTobias Grosser PPCGGen->kernel_id = 0; 2921f384594dSTobias Grosser 2922f384594dSTobias Grosser // Set scheduling strategy to same strategy PPCG is using. 2923f384594dSTobias Grosser isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2924f384594dSTobias Grosser isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 29252341fe9eSTobias Grosser isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2926f384594dSTobias Grosser 2927f384594dSTobias Grosser isl_schedule *Schedule = get_schedule(PPCGGen); 2928f384594dSTobias Grosser 2929aef5196fSTobias Grosser int has_permutable = has_any_permutable_node(Schedule); 2930aef5196fSTobias Grosser 293169b46751STobias Grosser if (!has_permutable || has_permutable < 0) { 2932aef5196fSTobias Grosser Schedule = isl_schedule_free(Schedule); 293369b46751STobias Grosser } else { 2934aef5196fSTobias Grosser Schedule = map_to_device(PPCGGen, Schedule); 293569b46751STobias Grosser PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 293669b46751STobias Grosser } 2937aef5196fSTobias Grosser 2938f384594dSTobias Grosser if (DumpSchedule) { 2939f384594dSTobias Grosser isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2940f384594dSTobias Grosser P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2941f384594dSTobias Grosser P = isl_printer_print_str(P, "Schedule\n"); 2942f384594dSTobias Grosser P = isl_printer_print_str(P, "========\n"); 2943f384594dSTobias Grosser if (Schedule) 2944f384594dSTobias Grosser P = isl_printer_print_schedule(P, Schedule); 2945f384594dSTobias Grosser else 2946f384594dSTobias Grosser P = isl_printer_print_str(P, "No schedule found\n"); 2947f384594dSTobias Grosser 2948f384594dSTobias Grosser printf("%s\n", isl_printer_get_str(P)); 2949f384594dSTobias Grosser isl_printer_free(P); 2950f384594dSTobias Grosser } 2951f384594dSTobias Grosser 295269b46751STobias Grosser if (DumpCode) { 295369b46751STobias Grosser printf("Code\n"); 295469b46751STobias Grosser printf("====\n"); 295569b46751STobias Grosser if (PPCGGen->tree) 295669b46751STobias Grosser printGPUTree(PPCGGen->tree, PPCGProg); 295769b46751STobias Grosser else 295869b46751STobias Grosser printf("No code generated\n"); 295969b46751STobias Grosser } 296069b46751STobias Grosser 2961f384594dSTobias Grosser isl_schedule_free(Schedule); 2962f384594dSTobias Grosser 2963f384594dSTobias Grosser return PPCGGen; 2964f384594dSTobias Grosser } 2965f384594dSTobias Grosser 2966f384594dSTobias Grosser /// Free gpu_gen structure. 2967f384594dSTobias Grosser /// 2968f384594dSTobias Grosser /// @param PPCGGen The ppcg_gen object to free. 2969f384594dSTobias Grosser void freePPCGGen(gpu_gen *PPCGGen) { 2970f384594dSTobias Grosser isl_ast_node_free(PPCGGen->tree); 2971f384594dSTobias Grosser isl_union_map_free(PPCGGen->sizes); 2972f384594dSTobias Grosser isl_union_map_free(PPCGGen->used_sizes); 2973f384594dSTobias Grosser free(PPCGGen); 2974f384594dSTobias Grosser } 2975f384594dSTobias Grosser 2976b307ed4dSTobias Grosser /// Free the options in the ppcg scop structure. 2977b307ed4dSTobias Grosser /// 2978b307ed4dSTobias Grosser /// ppcg is not freeing these options for us. To avoid leaks we do this 2979b307ed4dSTobias Grosser /// ourselves. 2980b307ed4dSTobias Grosser /// 2981b307ed4dSTobias Grosser /// @param PPCGScop The scop referencing the options to free. 2982b307ed4dSTobias Grosser void freeOptions(ppcg_scop *PPCGScop) { 2983b307ed4dSTobias Grosser free(PPCGScop->options->debug); 2984b307ed4dSTobias Grosser PPCGScop->options->debug = nullptr; 2985b307ed4dSTobias Grosser free(PPCGScop->options); 2986b307ed4dSTobias Grosser PPCGScop->options = nullptr; 2987b307ed4dSTobias Grosser } 2988b307ed4dSTobias Grosser 298982f2af35STobias Grosser /// Approximate the number of points in the set. 299082f2af35STobias Grosser /// 299182f2af35STobias Grosser /// This function returns an ast expression that overapproximates the number 299282f2af35STobias Grosser /// of points in an isl set through the rectangular hull surrounding this set. 299382f2af35STobias Grosser /// 299482f2af35STobias Grosser /// @param Set The set to count. 299582f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 299682f2af35STobias Grosser /// expression. 299782f2af35STobias Grosser /// 299882f2af35STobias Grosser /// @returns An approximation of the number of points in the set. 299982f2af35STobias Grosser __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 300082f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 300182f2af35STobias Grosser 300282f2af35STobias Grosser isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 300382f2af35STobias Grosser auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 300482f2af35STobias Grosser 300582f2af35STobias Grosser isl_space *Space = isl_set_get_space(Set); 300682f2af35STobias Grosser Space = isl_space_params(Space); 300782f2af35STobias Grosser auto *Univ = isl_set_universe(Space); 300882f2af35STobias Grosser isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 300982f2af35STobias Grosser 301082f2af35STobias Grosser for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 301182f2af35STobias Grosser isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 301282f2af35STobias Grosser isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 301382f2af35STobias Grosser isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 301482f2af35STobias Grosser DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 301582f2af35STobias Grosser auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 301682f2af35STobias Grosser Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 301782f2af35STobias Grosser } 301882f2af35STobias Grosser 301982f2af35STobias Grosser isl_set_free(Set); 302082f2af35STobias Grosser isl_pw_aff_free(OneAff); 302182f2af35STobias Grosser 302282f2af35STobias Grosser return Expr; 302382f2af35STobias Grosser } 302482f2af35STobias Grosser 302582f2af35STobias Grosser /// Approximate a number of dynamic instructions executed by a given 302682f2af35STobias Grosser /// statement. 302782f2af35STobias Grosser /// 302882f2af35STobias Grosser /// @param Stmt The statement for which to compute the number of dynamic 302982f2af35STobias Grosser /// instructions. 303082f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 303182f2af35STobias Grosser /// expression. 303282f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 303382f2af35STobias Grosser /// by @p Stmt. 303482f2af35STobias Grosser __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 303582f2af35STobias Grosser __isl_keep isl_ast_build *Build) { 303682f2af35STobias Grosser auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 303782f2af35STobias Grosser 303882f2af35STobias Grosser long InstCount = 0; 303982f2af35STobias Grosser 304082f2af35STobias Grosser if (Stmt.isBlockStmt()) { 304182f2af35STobias Grosser auto *BB = Stmt.getBasicBlock(); 304282f2af35STobias Grosser InstCount = std::distance(BB->begin(), BB->end()); 304382f2af35STobias Grosser } else { 304482f2af35STobias Grosser auto *R = Stmt.getRegion(); 304582f2af35STobias Grosser 304682f2af35STobias Grosser for (auto *BB : R->blocks()) { 304782f2af35STobias Grosser InstCount += std::distance(BB->begin(), BB->end()); 304882f2af35STobias Grosser } 304982f2af35STobias Grosser } 305082f2af35STobias Grosser 305182f2af35STobias Grosser isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 305282f2af35STobias Grosser auto *InstExpr = isl_ast_expr_from_val(InstVal); 305382f2af35STobias Grosser return isl_ast_expr_mul(InstExpr, Iterations); 305482f2af35STobias Grosser } 305582f2af35STobias Grosser 305682f2af35STobias Grosser /// Approximate dynamic instructions executed in scop. 305782f2af35STobias Grosser /// 305882f2af35STobias Grosser /// @param S The scop for which to approximate dynamic instructions. 305982f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 306082f2af35STobias Grosser /// expression. 306182f2af35STobias Grosser /// @returns An approximation of the number of dynamic instructions executed 306282f2af35STobias Grosser /// in @p S. 306382f2af35STobias Grosser __isl_give isl_ast_expr * 306482f2af35STobias Grosser getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 306582f2af35STobias Grosser isl_ast_expr *Instructions; 306682f2af35STobias Grosser 306782f2af35STobias Grosser isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 306882f2af35STobias Grosser Instructions = isl_ast_expr_from_val(Zero); 306982f2af35STobias Grosser 307082f2af35STobias Grosser for (ScopStmt &Stmt : S) { 307182f2af35STobias Grosser isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 307282f2af35STobias Grosser Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 307382f2af35STobias Grosser } 307482f2af35STobias Grosser return Instructions; 307582f2af35STobias Grosser } 307682f2af35STobias Grosser 307782f2af35STobias Grosser /// Create a check that ensures sufficient compute in scop. 307882f2af35STobias Grosser /// 307982f2af35STobias Grosser /// @param S The scop for which to ensure sufficient compute. 308082f2af35STobias Grosser /// @param Build The isl ast build object to use for creating the ast 308182f2af35STobias Grosser /// expression. 308282f2af35STobias Grosser /// @returns An expression that evaluates to TRUE in case of sufficient 308382f2af35STobias Grosser /// compute and to FALSE, otherwise. 308482f2af35STobias Grosser __isl_give isl_ast_expr * 308582f2af35STobias Grosser createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 308682f2af35STobias Grosser auto Iterations = getNumberOfIterations(S, Build); 308782f2af35STobias Grosser auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 308882f2af35STobias Grosser auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 308982f2af35STobias Grosser return isl_ast_expr_ge(Iterations, MinComputeExpr); 309082f2af35STobias Grosser } 309182f2af35STobias Grosser 3092f291c8d5SSiddharth Bhat /// Check if the basic block contains a function we cannot codegen for GPU 3093f291c8d5SSiddharth Bhat /// kernels. 3094f291c8d5SSiddharth Bhat /// 3095f291c8d5SSiddharth Bhat /// If this basic block does something with a `Function` other than calling 3096f291c8d5SSiddharth Bhat /// a function that we support in a kernel, return true. 3097018103d3STobias Grosser bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) { 3098f291c8d5SSiddharth Bhat for (const Instruction &Inst : *BB) { 3099f291c8d5SSiddharth Bhat const CallInst *Call = dyn_cast<CallInst>(&Inst); 3100f291c8d5SSiddharth Bhat if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 3101f291c8d5SSiddharth Bhat continue; 3102f291c8d5SSiddharth Bhat } 3103f291c8d5SSiddharth Bhat 3104bccaea57SSiddharth Bhat for (Value *SrcVal : Inst.operands()) { 3105bccaea57SSiddharth Bhat PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3106bccaea57SSiddharth Bhat if (!p) 3107bccaea57SSiddharth Bhat continue; 3108bccaea57SSiddharth Bhat if (isa<FunctionType>(p->getElementType())) 3109bccaea57SSiddharth Bhat return true; 3110bccaea57SSiddharth Bhat } 3111f291c8d5SSiddharth Bhat } 3112bccaea57SSiddharth Bhat return false; 3113bccaea57SSiddharth Bhat } 3114bccaea57SSiddharth Bhat 3115f291c8d5SSiddharth Bhat /// Return whether the Scop S uses functions in a way that we do not support. 3116f291c8d5SSiddharth Bhat bool containsInvalidKernelFunction(const Scop &S) { 3117bccaea57SSiddharth Bhat for (auto &Stmt : S) { 3118bccaea57SSiddharth Bhat if (Stmt.isBlockStmt()) { 3119018103d3STobias Grosser if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock())) 3120bccaea57SSiddharth Bhat return true; 3121bccaea57SSiddharth Bhat } else { 3122bccaea57SSiddharth Bhat assert(Stmt.isRegionStmt() && 3123bccaea57SSiddharth Bhat "Stmt was neither block nor region statement"); 3124bccaea57SSiddharth Bhat for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 3125018103d3STobias Grosser if (containsInvalidKernelFunctionInBlock(BB)) 3126bccaea57SSiddharth Bhat return true; 3127bccaea57SSiddharth Bhat } 3128bccaea57SSiddharth Bhat } 3129bccaea57SSiddharth Bhat return false; 3130bccaea57SSiddharth Bhat } 3131bccaea57SSiddharth Bhat 313238fc0aedSTobias Grosser /// Generate code for a given GPU AST described by @p Root. 313338fc0aedSTobias Grosser /// 313432837fe3STobias Grosser /// @param Root An isl_ast_node pointing to the root of the GPU AST. 313532837fe3STobias Grosser /// @param Prog The GPU Program to generate code for. 313632837fe3STobias Grosser void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 313738fc0aedSTobias Grosser ScopAnnotator Annotator; 313838fc0aedSTobias Grosser Annotator.buildAliasScopes(*S); 313938fc0aedSTobias Grosser 314038fc0aedSTobias Grosser Region *R = &S->getRegion(); 314138fc0aedSTobias Grosser 314238fc0aedSTobias Grosser simplifyRegion(R, DT, LI, RI); 314338fc0aedSTobias Grosser 314438fc0aedSTobias Grosser BasicBlock *EnteringBB = R->getEnteringBlock(); 314538fc0aedSTobias Grosser 314638fc0aedSTobias Grosser PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 314738fc0aedSTobias Grosser 314838fc0aedSTobias Grosser // Only build the run-time condition and parameters _after_ having 314938fc0aedSTobias Grosser // introduced the conditional branch. This is important as the conditional 315038fc0aedSTobias Grosser // branch will guard the original scop from new induction variables that 315138fc0aedSTobias Grosser // the SCEVExpander may introduce while code generating the parameters and 315238fc0aedSTobias Grosser // which may introduce scalar dependences that prevent us from correctly 315338fc0aedSTobias Grosser // code generating this scop. 315403346c27SSiddharth Bhat BBPair StartExitBlocks; 315503346c27SSiddharth Bhat BranchInst *CondBr = nullptr; 315603346c27SSiddharth Bhat std::tie(StartExitBlocks, CondBr) = 31572d950f36SPhilip Pfaffe executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3158256070d8SAndreas Simbuerger BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 315938fc0aedSTobias Grosser 316003346c27SSiddharth Bhat assert(CondBr && "CondBr not initialized by executeScopConditionally"); 316103346c27SSiddharth Bhat 31622d950f36SPhilip Pfaffe GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 316317f01968SSiddharth Bhat StartBlock, Prog, Runtime, Architecture); 3164acf80064SEli Friedman 316538fc0aedSTobias Grosser // TODO: Handle LICM 316638fc0aedSTobias Grosser auto SplitBlock = StartBlock->getSinglePredecessor(); 316738fc0aedSTobias Grosser Builder.SetInsertPoint(SplitBlock->getTerminator()); 316838fc0aedSTobias Grosser NodeBuilder.addParameters(S->getContext()); 3169cb1aef8dSTobias Grosser 3170cb1aef8dSTobias Grosser isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 31712b852e2eSPhilip Pfaffe isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 317282f2af35STobias Grosser isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 317382f2af35STobias Grosser Condition = isl_ast_expr_and(Condition, SufficientCompute); 3174cb1aef8dSTobias Grosser isl_ast_build_free(Build); 3175cb1aef8dSTobias Grosser 31769e3db2b7SSiddharth Bhat // preload invariant loads. Note: This should happen before the RTC 31779e3db2b7SSiddharth Bhat // because the RTC may depend on values that are invariant load hoisted. 31789e3db2b7SSiddharth Bhat NodeBuilder.preloadInvariantLoads(); 31799e3db2b7SSiddharth Bhat 3180cb1aef8dSTobias Grosser Value *RTC = NodeBuilder.createRTC(Condition); 3181cb1aef8dSTobias Grosser Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3182cb1aef8dSTobias Grosser 318338fc0aedSTobias Grosser Builder.SetInsertPoint(&*StartBlock->begin()); 3184fa7b0802STobias Grosser 318538fc0aedSTobias Grosser NodeBuilder.create(Root); 31865857b701STobias Grosser 3187bc653f20STobias Grosser /// In case a sequential kernel has more surrounding loops as any parallel 3188bc653f20STobias Grosser /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3189de244eb4STobias Grosser /// point in running it on a GPU. 3190bc653f20STobias Grosser if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 319103346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 3192bc653f20STobias Grosser 31935857b701STobias Grosser if (!NodeBuilder.BuildSuccessful) 319403346c27SSiddharth Bhat CondBr->setOperand(0, Builder.getFalse()); 319538fc0aedSTobias Grosser } 319638fc0aedSTobias Grosser 3197e938517eSTobias Grosser bool runOnScop(Scop &CurrentScop) override { 3198e938517eSTobias Grosser S = &CurrentScop; 319938fc0aedSTobias Grosser LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 320038fc0aedSTobias Grosser DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 320138fc0aedSTobias Grosser SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 32027b5a4dfdSTobias Grosser DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 320338fc0aedSTobias Grosser RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3204e938517eSTobias Grosser 3205f291c8d5SSiddharth Bhat // We currently do not support functions other than intrinsics inside 3206f291c8d5SSiddharth Bhat // kernels, as code generation will need to offload function calls to the 3207f291c8d5SSiddharth Bhat // kernel. This may lead to a kernel trying to call a function on the host. 3208bccaea57SSiddharth Bhat // This also allows us to prevent codegen from trying to take the 3209bccaea57SSiddharth Bhat // address of an intrinsic function to send to the kernel. 3210f291c8d5SSiddharth Bhat if (containsInvalidKernelFunction(CurrentScop)) { 3211f291c8d5SSiddharth Bhat DEBUG( 3212f291c8d5SSiddharth Bhat dbgs() 3213f291c8d5SSiddharth Bhat << "Scop contains function which cannot be materialised in a GPU " 3214f291c8d5SSiddharth Bhat "kernel. Bailing out.\n";); 3215bccaea57SSiddharth Bhat return false; 3216f291c8d5SSiddharth Bhat } 3217bccaea57SSiddharth Bhat 3218e938517eSTobias Grosser auto PPCGScop = createPPCGScop(); 3219e938517eSTobias Grosser auto PPCGProg = createPPCGProg(PPCGScop); 3220f384594dSTobias Grosser auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 322138fc0aedSTobias Grosser 322202ca346eSSingapuram Sanjay Srivallabh if (PPCGGen->tree) { 322332837fe3STobias Grosser generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 322402ca346eSSingapuram Sanjay Srivallabh CurrentScop.markAsToBeSkipped(); 322502ca346eSSingapuram Sanjay Srivallabh } 322638fc0aedSTobias Grosser 3227b307ed4dSTobias Grosser freeOptions(PPCGScop); 3228f384594dSTobias Grosser freePPCGGen(PPCGGen); 3229e938517eSTobias Grosser gpu_prog_free(PPCGProg); 3230e938517eSTobias Grosser ppcg_scop_free(PPCGScop); 3231e938517eSTobias Grosser 3232e938517eSTobias Grosser return true; 3233e938517eSTobias Grosser } 32349dfe4e7cSTobias Grosser 32359dfe4e7cSTobias Grosser void printScop(raw_ostream &, Scop &) const override {} 32369dfe4e7cSTobias Grosser 32379dfe4e7cSTobias Grosser void getAnalysisUsage(AnalysisUsage &AU) const override { 32389dfe4e7cSTobias Grosser AU.addRequired<DominatorTreeWrapperPass>(); 32399dfe4e7cSTobias Grosser AU.addRequired<RegionInfoPass>(); 32409dfe4e7cSTobias Grosser AU.addRequired<ScalarEvolutionWrapperPass>(); 32415cc87e3aSPhilip Pfaffe AU.addRequired<ScopDetectionWrapperPass>(); 32429dfe4e7cSTobias Grosser AU.addRequired<ScopInfoRegionPass>(); 32439dfe4e7cSTobias Grosser AU.addRequired<LoopInfoWrapperPass>(); 32449dfe4e7cSTobias Grosser 32459dfe4e7cSTobias Grosser AU.addPreserved<AAResultsWrapperPass>(); 32469dfe4e7cSTobias Grosser AU.addPreserved<BasicAAWrapperPass>(); 32479dfe4e7cSTobias Grosser AU.addPreserved<LoopInfoWrapperPass>(); 32489dfe4e7cSTobias Grosser AU.addPreserved<DominatorTreeWrapperPass>(); 32499dfe4e7cSTobias Grosser AU.addPreserved<GlobalsAAWrapperPass>(); 32505cc87e3aSPhilip Pfaffe AU.addPreserved<ScopDetectionWrapperPass>(); 32519dfe4e7cSTobias Grosser AU.addPreserved<ScalarEvolutionWrapperPass>(); 32529dfe4e7cSTobias Grosser AU.addPreserved<SCEVAAWrapperPass>(); 32539dfe4e7cSTobias Grosser 32549dfe4e7cSTobias Grosser // FIXME: We do not yet add regions for the newly generated code to the 32559dfe4e7cSTobias Grosser // region tree. 32569dfe4e7cSTobias Grosser AU.addPreserved<RegionInfoPass>(); 32579dfe4e7cSTobias Grosser AU.addPreserved<ScopInfoRegionPass>(); 32589dfe4e7cSTobias Grosser } 32599dfe4e7cSTobias Grosser }; 326024222c73STobias Grosser } // namespace 32619dfe4e7cSTobias Grosser 32629dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1; 32639dfe4e7cSTobias Grosser 326417f01968SSiddharth Bhat Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 326517f01968SSiddharth Bhat PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 326617f01968SSiddharth Bhat generator->Runtime = Runtime; 326717f01968SSiddharth Bhat generator->Architecture = Arch; 326817f01968SSiddharth Bhat return generator; 326917f01968SSiddharth Bhat } 32709dfe4e7cSTobias Grosser 32719dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 32729dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 32739dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 32749dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 32759dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 32769dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 32779dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 32785cc87e3aSPhilip Pfaffe INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 32799dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 32809dfe4e7cSTobias Grosser "Polly - Apply PPCG translation to SCOP", false, false) 3281