1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Take a scop created by ScopInfo and map it to GPU code using the ppcg 10 // GPU mapping strategy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "polly/CodeGen/PPCGCodeGeneration.h" 15 #include "polly/CodeGen/CodeGeneration.h" 16 #include "polly/CodeGen/IslAst.h" 17 #include "polly/CodeGen/IslNodeBuilder.h" 18 #include "polly/CodeGen/PerfMonitor.h" 19 #include "polly/CodeGen/Utils.h" 20 #include "polly/DependenceInfo.h" 21 #include "polly/LinkAllPasses.h" 22 #include "polly/Options.h" 23 #include "polly/ScopDetection.h" 24 #include "polly/ScopInfo.h" 25 #include "polly/Support/ISLTools.h" 26 #include "polly/Support/SCEVValidator.h" 27 #include "llvm/ADT/PostOrderIterator.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/IR/IntrinsicsNVPTX.h" 30 #include "llvm/IR/LegacyPassManager.h" 31 #include "llvm/IR/Verifier.h" 32 #include "llvm/IRReader/IRReader.h" 33 #include "llvm/InitializePasses.h" 34 #include "llvm/Linker/Linker.h" 35 #include "llvm/MC/TargetRegistry.h" 36 #include "llvm/Support/SourceMgr.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 39 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40 #include "isl/union_map.h" 41 #include <algorithm> 42 43 extern "C" { 44 #include "ppcg/cuda.h" 45 #include "ppcg/gpu.h" 46 #include "ppcg/ppcg.h" 47 } 48 49 #include "llvm/Support/Debug.h" 50 51 using namespace polly; 52 using namespace llvm; 53 54 #define DEBUG_TYPE "polly-codegen-ppcg" 55 56 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 57 cl::desc("Dump the computed GPU Schedule"), 58 cl::Hidden, cl::cat(PollyCategory)); 59 60 static cl::opt<bool> 61 DumpCode("polly-acc-dump-code", 62 cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 63 cl::cat(PollyCategory)); 64 65 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 66 cl::desc("Dump the kernel LLVM-IR"), 67 cl::Hidden, cl::cat(PollyCategory)); 68 69 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 70 cl::desc("Dump the kernel assembly code"), 71 cl::Hidden, cl::cat(PollyCategory)); 72 73 static cl::opt<bool> FastMath("polly-acc-fastmath", 74 cl::desc("Allow unsafe math optimizations"), 75 cl::Hidden, cl::cat(PollyCategory)); 76 static cl::opt<bool> SharedMemory("polly-acc-use-shared", 77 cl::desc("Use shared memory"), cl::Hidden, 78 cl::cat(PollyCategory)); 79 static cl::opt<bool> PrivateMemory("polly-acc-use-private", 80 cl::desc("Use private memory"), cl::Hidden, 81 cl::cat(PollyCategory)); 82 83 bool polly::PollyManagedMemory; 84 static cl::opt<bool, true> 85 XManagedMemory("polly-acc-codegen-managed-memory", 86 cl::desc("Generate Host kernel code assuming" 87 " that all memory has been" 88 " declared as managed memory"), 89 cl::location(PollyManagedMemory), cl::Hidden, 90 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 91 92 static cl::opt<bool> 93 FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 94 cl::desc("Fail and generate a backtrace if" 95 " verifyModule fails on the GPU " 96 " kernel module."), 97 cl::Hidden, cl::init(false), cl::ZeroOrMore, 98 cl::cat(PollyCategory)); 99 100 static cl::opt<std::string> CUDALibDevice( 101 "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden, 102 cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"), 103 cl::ZeroOrMore, cl::cat(PollyCategory)); 104 105 static cl::opt<std::string> 106 CudaVersion("polly-acc-cuda-version", 107 cl::desc("The CUDA version to compile for"), cl::Hidden, 108 cl::init("sm_30"), cl::cat(PollyCategory)); 109 110 static cl::opt<int> 111 MinCompute("polly-acc-mincompute", 112 cl::desc("Minimal number of compute statements to run on GPU."), 113 cl::Hidden, cl::init(10 * 512 * 512)); 114 115 GPURuntime polly::GPURuntimeChoice; 116 static cl::opt<GPURuntime, true> XGPURuntimeChoice( 117 "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"), 118 cl::values(clEnumValN(GPURuntime::CUDA, "libcudart", 119 "use the CUDA Runtime API"), 120 clEnumValN(GPURuntime::OpenCL, "libopencl", 121 "use the OpenCL Runtime API")), 122 cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA), 123 cl::ZeroOrMore, cl::cat(PollyCategory)); 124 125 GPUArch polly::GPUArchChoice; 126 static cl::opt<GPUArch, true> 127 XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"), 128 cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64", 129 "target NVIDIA 64-bit architecture"), 130 clEnumValN(GPUArch::SPIR32, "spir32", 131 "target SPIR 32-bit architecture"), 132 clEnumValN(GPUArch::SPIR64, "spir64", 133 "target SPIR 64-bit architecture")), 134 cl::location(polly::GPUArchChoice), 135 cl::init(GPUArch::NVPTX64), cl::ZeroOrMore, 136 cl::cat(PollyCategory)); 137 138 extern bool polly::PerfMonitoring; 139 140 /// Return a unique name for a Scop, which is the scop region with the 141 /// function name. 142 std::string getUniqueScopName(const Scop *S) { 143 return "Scop Region: " + S->getNameStr() + 144 " | Function: " + std::string(S->getFunction().getName()); 145 } 146 147 /// Used to store information PPCG wants for kills. This information is 148 /// used by live range reordering. 149 /// 150 /// @see computeLiveRangeReordering 151 /// @see GPUNodeBuilder::createPPCGScop 152 /// @see GPUNodeBuilder::createPPCGProg 153 struct MustKillsInfo { 154 /// Collection of all kill statements that will be sequenced at the end of 155 /// PPCGScop->schedule. 156 /// 157 /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 158 /// which merges schedules in *arbitrary* order. 159 /// (we don't care about the order of the kills anyway). 160 isl::schedule KillsSchedule; 161 /// Map from kill statement instances to scalars that need to be 162 /// killed. 163 /// 164 /// We currently derive kill information for: 165 /// 1. phi nodes. PHI nodes are not alive outside the scop and can 166 /// consequently all be killed. 167 /// 2. Scalar arrays that are not used outside the Scop. This is 168 /// checked by `isScalarUsesContainedInScop`. 169 /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 170 isl::union_map TaggedMustKills; 171 172 /// Tagged must kills stripped of the tags. 173 /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 174 isl::union_map MustKills; 175 176 MustKillsInfo() : KillsSchedule() {} 177 }; 178 179 /// Check if SAI's uses are entirely contained within Scop S. 180 /// If a scalar is used only with a Scop, we are free to kill it, as no data 181 /// can flow in/out of the value any more. 182 /// @see computeMustKillsInfo 183 static bool isScalarUsesContainedInScop(const Scop &S, 184 const ScopArrayInfo *SAI) { 185 assert(SAI->isValueKind() && "this function only deals with scalars." 186 " Dealing with arrays required alias analysis"); 187 188 const Region &R = S.getRegion(); 189 for (User *U : SAI->getBasePtr()->users()) { 190 Instruction *I = dyn_cast<Instruction>(U); 191 assert(I && "invalid user of scop array info"); 192 if (!R.contains(I)) 193 return false; 194 } 195 return true; 196 } 197 198 /// Compute must-kills needed to enable live range reordering with PPCG. 199 /// 200 /// @params S The Scop to compute live range reordering information 201 /// @returns live range reordering information that can be used to setup 202 /// PPCG. 203 static MustKillsInfo computeMustKillsInfo(const Scop &S) { 204 const isl::space ParamSpace = S.getParamSpace(); 205 MustKillsInfo Info; 206 207 // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 208 // 1.1 phi nodes in scop. 209 // 1.2 scalars that are only used within the scop 210 SmallVector<isl::id, 4> KillMemIds; 211 for (ScopArrayInfo *SAI : S.arrays()) { 212 if (SAI->isPHIKind() || 213 (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 214 KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release())); 215 } 216 217 Info.TaggedMustKills = isl::union_map::empty(ParamSpace.ctx()); 218 Info.MustKills = isl::union_map::empty(ParamSpace.ctx()); 219 220 // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 221 // schedule: 222 // - filter: "[control] -> { }" 223 // So, we choose to not create this to keep the output a little nicer, 224 // at the cost of some code complexity. 225 Info.KillsSchedule = {}; 226 227 for (isl::id &ToKillId : KillMemIds) { 228 isl::id KillStmtId = isl::id::alloc( 229 S.getIslCtx(), 230 std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 231 232 // NOTE: construction of tagged_must_kill: 233 // 2. We need to construct a map: 234 // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 235 // To construct this, we use `isl_map_domain_product` on 2 maps`: 236 // 2a. StmtToScalar: 237 // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 238 // 2b. PhantomRefToScalar: 239 // [param] -> { ref_phantom[] -> scalar_to_kill[] } 240 // 241 // Combining these with `isl_map_domain_product` gives us 242 // TaggedMustKill: 243 // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 244 245 // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 246 isl::map StmtToScalar = isl::map::universe(ParamSpace); 247 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 248 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 249 250 isl::id PhantomRefId = isl::id::alloc( 251 S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 252 nullptr); 253 254 // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 255 isl::map PhantomRefToScalar = isl::map::universe(ParamSpace); 256 PhantomRefToScalar = 257 PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 258 PhantomRefToScalar = 259 PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 260 261 // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 262 isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 263 Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 264 265 // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 266 Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 267 268 // 3. Create the kill schedule of the form: 269 // "[param] -> { Stmt_phantom[] }" 270 // Then add this to Info.KillsSchedule. 271 isl::space KillStmtSpace = ParamSpace; 272 KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 273 isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 274 275 isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 276 if (!Info.KillsSchedule.is_null()) 277 Info.KillsSchedule = isl::manage( 278 isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy())); 279 else 280 Info.KillsSchedule = KillSchedule; 281 } 282 283 return Info; 284 } 285 286 /// Create the ast expressions for a ScopStmt. 287 /// 288 /// This function is a callback for to generate the ast expressions for each 289 /// of the scheduled ScopStmts. 290 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 291 void *StmtT, __isl_take isl_ast_build *Build_C, 292 isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 293 isl_id *Id, void *User), 294 void *UserIndex, 295 isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 296 void *UserExpr) { 297 298 ScopStmt *Stmt = (ScopStmt *)StmtT; 299 300 if (!Stmt || !Build_C) 301 return NULL; 302 303 isl::ast_build Build = isl::manage_copy(Build_C); 304 isl::ctx Ctx = Build.ctx(); 305 isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0); 306 307 Stmt->setAstBuild(Build); 308 309 for (MemoryAccess *Acc : *Stmt) { 310 isl::map AddrFunc = Acc->getAddressFunction(); 311 AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain()); 312 313 isl::id RefId = Acc->getId(); 314 isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc); 315 316 isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA); 317 MPA = MPA.coalesce(); 318 MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex)); 319 320 isl::ast_expr Access = Build.access_from(MPA); 321 Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr)); 322 RefToExpr = RefToExpr.set(RefId, Access); 323 } 324 325 return RefToExpr.release(); 326 } 327 328 /// Given a LLVM Type, compute its size in bytes, 329 static int computeSizeInBytes(const Type *T) { 330 int bytes = T->getPrimitiveSizeInBits() / 8; 331 if (bytes == 0) 332 bytes = T->getScalarSizeInBits() / 8; 333 return bytes; 334 } 335 336 /// Generate code for a GPU specific isl AST. 337 /// 338 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 339 /// generates code for general-purpose AST nodes, with special functionality 340 /// for generating GPU specific user nodes. 341 /// 342 /// @see GPUNodeBuilder::createUser 343 class GPUNodeBuilder final : public IslNodeBuilder { 344 public: 345 GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 346 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 347 DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 348 gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 349 : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 350 Prog(Prog), Runtime(Runtime), Arch(Arch) { 351 getExprBuilder().setIDToSAI(&IDToSAI); 352 } 353 354 /// Create after-run-time-check initialization code. 355 void initializeAfterRTH(); 356 357 /// Finalize the generated scop. 358 void finalize() override; 359 360 /// Track if the full build process was successful. 361 /// 362 /// This value is set to false, if throughout the build process an error 363 /// occurred which prevents us from generating valid GPU code. 364 bool BuildSuccessful = true; 365 366 /// The maximal number of loops surrounding a sequential kernel. 367 unsigned DeepestSequential = 0; 368 369 /// The maximal number of loops surrounding a parallel kernel. 370 unsigned DeepestParallel = 0; 371 372 /// Return the name to set for the ptx_kernel. 373 std::string getKernelFuncName(int Kernel_id); 374 375 private: 376 /// A vector of array base pointers for which a new ScopArrayInfo was created. 377 /// 378 /// This vector is used to delete the ScopArrayInfo when it is not needed any 379 /// more. 380 std::vector<Value *> LocalArrays; 381 382 /// A map from ScopArrays to their corresponding device allocations. 383 std::map<ScopArrayInfo *, Value *> DeviceAllocations; 384 385 /// The current GPU context. 386 Value *GPUContext; 387 388 /// The set of isl_ids allocated in the kernel 389 std::vector<isl_id *> KernelIds; 390 391 /// A module containing GPU code. 392 /// 393 /// This pointer is only set in case we are currently generating GPU code. 394 std::unique_ptr<Module> GPUModule; 395 396 /// The GPU program we generate code for. 397 gpu_prog *Prog; 398 399 /// The GPU Runtime implementation to use (OpenCL or CUDA). 400 GPURuntime Runtime; 401 402 /// The GPU Architecture to target. 403 GPUArch Arch; 404 405 /// Class to free isl_ids. 406 class IslIdDeleter final { 407 public: 408 void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 409 }; 410 411 /// A set containing all isl_ids allocated in a GPU kernel. 412 /// 413 /// By releasing this set all isl_ids will be freed. 414 std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 415 416 IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 417 418 /// Create code for user-defined AST nodes. 419 /// 420 /// These AST nodes can be of type: 421 /// 422 /// - ScopStmt: A computational statement (TODO) 423 /// - Kernel: A GPU kernel call (TODO) 424 /// - Data-Transfer: A GPU <-> CPU data-transfer 425 /// - In-kernel synchronization 426 /// - In-kernel memory copy statement 427 /// 428 /// @param UserStmt The ast node to generate code for. 429 void createUser(__isl_take isl_ast_node *UserStmt) override; 430 431 void createFor(__isl_take isl_ast_node *Node) override; 432 433 enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 434 435 /// Create code for a data transfer statement 436 /// 437 /// @param TransferStmt The data transfer statement. 438 /// @param Direction The direction in which to transfer data. 439 void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 440 enum DataDirection Direction); 441 442 /// Find llvm::Values referenced in GPU kernel. 443 /// 444 /// @param Kernel The kernel to scan for llvm::Values 445 /// 446 /// @returns A tuple, whose: 447 /// - First element contains the set of values referenced by the 448 /// kernel 449 /// - Second element contains the set of functions referenced by the 450 /// kernel. All functions in the set satisfy 451 /// `isValidFunctionInKernel`. 452 /// - Third element contains loops that have induction variables 453 /// which are used in the kernel, *and* these loops are *neither* 454 /// in the scop, nor do they immediately surroung the Scop. 455 /// See [Code generation of induction variables of loops outside 456 /// Scops] 457 std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 458 isl::space> 459 getReferencesInKernel(ppcg_kernel *Kernel); 460 461 /// Compute the sizes of the execution grid for a given kernel. 462 /// 463 /// @param Kernel The kernel to compute grid sizes for. 464 /// 465 /// @returns A tuple with grid sizes for X and Y dimension 466 std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 467 468 /// Get the managed array pointer for sending host pointers to the device. 469 /// \note 470 /// This is to be used only with managed memory 471 Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo); 472 473 /// Compute the sizes of the thread blocks for a given kernel. 474 /// 475 /// @param Kernel The kernel to compute thread block sizes for. 476 /// 477 /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 478 std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 479 480 /// Store a specific kernel launch parameter in the array of kernel launch 481 /// parameters. 482 /// 483 /// @param ArrayTy Array type of \p Parameters. 484 /// @param Parameters The list of parameters in which to store. 485 /// @param Param The kernel launch parameter to store. 486 /// @param Index The index in the parameter list, at which to store the 487 /// parameter. 488 void insertStoreParameter(Type *ArrayTy, Instruction *Parameters, 489 Instruction *Param, int Index); 490 491 /// Create kernel launch parameters. 492 /// 493 /// @param Kernel The kernel to create parameters for. 494 /// @param F The kernel function that has been created. 495 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 496 /// 497 /// @returns A stack allocated array with pointers to the parameter 498 /// values that are passed to the kernel. 499 Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 500 SetVector<Value *> SubtreeValues); 501 502 /// Create declarations for kernel variable. 503 /// 504 /// This includes shared memory declarations. 505 /// 506 /// @param Kernel The kernel definition to create variables for. 507 /// @param FN The function into which to generate the variables. 508 void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 509 510 /// Add CUDA annotations to module. 511 /// 512 /// Add a set of CUDA annotations that declares the maximal block dimensions 513 /// that will be used to execute the CUDA kernel. This allows the NVIDIA 514 /// PTX compiler to bound the number of allocated registers to ensure the 515 /// resulting kernel is known to run with up to as many block dimensions 516 /// as specified here. 517 /// 518 /// @param M The module to add the annotations to. 519 /// @param BlockDimX The size of block dimension X. 520 /// @param BlockDimY The size of block dimension Y. 521 /// @param BlockDimZ The size of block dimension Z. 522 void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 523 Value *BlockDimZ); 524 525 /// Create GPU kernel. 526 /// 527 /// Code generate the kernel described by @p KernelStmt. 528 /// 529 /// @param KernelStmt The ast node to generate kernel code for. 530 void createKernel(__isl_take isl_ast_node *KernelStmt); 531 532 /// Generate code that computes the size of an array. 533 /// 534 /// @param Array The array for which to compute a size. 535 Value *getArraySize(gpu_array_info *Array); 536 537 /// Generate code to compute the minimal offset at which an array is accessed. 538 /// 539 /// The offset of an array is the minimal array location accessed in a scop. 540 /// 541 /// Example: 542 /// 543 /// for (long i = 0; i < 100; i++) 544 /// A[i + 42] += ... 545 /// 546 /// getArrayOffset(A) results in 42. 547 /// 548 /// @param Array The array for which to compute the offset. 549 /// @returns An llvm::Value that contains the offset of the array. 550 Value *getArrayOffset(gpu_array_info *Array); 551 552 /// Prepare the kernel arguments for kernel code generation 553 /// 554 /// @param Kernel The kernel to generate code for. 555 /// @param FN The function created for the kernel. 556 void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 557 558 /// Create kernel function. 559 /// 560 /// Create a kernel function located in a newly created module that can serve 561 /// as target for device code generation. Set the Builder to point to the 562 /// start block of this newly created function. 563 /// 564 /// @param Kernel The kernel to generate code for. 565 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 566 /// @param SubtreeFunctions The set of llvm::Functions referenced by this 567 /// kernel. 568 void createKernelFunction(ppcg_kernel *Kernel, 569 SetVector<Value *> &SubtreeValues, 570 SetVector<Function *> &SubtreeFunctions); 571 572 /// Create the declaration of a kernel function. 573 /// 574 /// The kernel function takes as arguments: 575 /// 576 /// - One i8 pointer for each external array reference used in the kernel. 577 /// - Host iterators 578 /// - Parameters 579 /// - Other LLVM Value references (TODO) 580 /// 581 /// @param Kernel The kernel to generate the function declaration for. 582 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 583 /// 584 /// @returns The newly declared function. 585 Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 586 SetVector<Value *> &SubtreeValues); 587 588 /// Insert intrinsic functions to obtain thread and block ids. 589 /// 590 /// @param The kernel to generate the intrinsic functions for. 591 void insertKernelIntrinsics(ppcg_kernel *Kernel); 592 593 /// Insert function calls to retrieve the SPIR group/local ids. 594 /// 595 /// @param Kernel The kernel to generate the function calls for. 596 /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit. 597 void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit); 598 599 /// Setup the creation of functions referenced by the GPU kernel. 600 /// 601 /// 1. Create new function declarations in GPUModule which are the same as 602 /// SubtreeFunctions. 603 /// 604 /// 2. Populate IslNodeBuilder::ValueMap with mappings from 605 /// old functions (that come from the original module) to new functions 606 /// (that are created within GPUModule). That way, we generate references 607 /// to the correct function (in GPUModule) in BlockGenerator. 608 /// 609 /// @see IslNodeBuilder::ValueMap 610 /// @see BlockGenerator::GlobalMap 611 /// @see BlockGenerator::getNewValue 612 /// @see GPUNodeBuilder::getReferencesInKernel. 613 /// 614 /// @param SubtreeFunctions The set of llvm::Functions referenced by 615 /// this kernel. 616 void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 617 618 /// Create a global-to-shared or shared-to-global copy statement. 619 /// 620 /// @param CopyStmt The copy statement to generate code for 621 void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 622 623 /// Create code for a ScopStmt called in @p Expr. 624 /// 625 /// @param Expr The expression containing the call. 626 /// @param KernelStmt The kernel statement referenced in the call. 627 void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 628 629 /// Create an in-kernel synchronization call. 630 void createKernelSync(); 631 632 /// Create a PTX assembly string for the current GPU kernel. 633 /// 634 /// @returns A string containing the corresponding PTX assembly code. 635 std::string createKernelASM(); 636 637 /// Remove references from the dominator tree to the kernel function @p F. 638 /// 639 /// @param F The function to remove references to. 640 void clearDominators(Function *F); 641 642 /// Remove references from scalar evolution to the kernel function @p F. 643 /// 644 /// @param F The function to remove references to. 645 void clearScalarEvolution(Function *F); 646 647 /// Remove references from loop info to the kernel function @p F. 648 /// 649 /// @param F The function to remove references to. 650 void clearLoops(Function *F); 651 652 /// Check if the scop requires to be linked with CUDA's libdevice. 653 bool requiresCUDALibDevice(); 654 655 /// Link with the NVIDIA libdevice library (if needed and available). 656 void addCUDALibDevice(); 657 658 /// Finalize the generation of the kernel function. 659 /// 660 /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 661 /// dump its IR to stderr. 662 /// 663 /// @returns The Assembly string of the kernel. 664 std::string finalizeKernelFunction(); 665 666 /// Finalize the generation of the kernel arguments. 667 /// 668 /// This function ensures that not-read-only scalars used in a kernel are 669 /// stored back to the global memory location they are backed with before 670 /// the kernel terminates. 671 /// 672 /// @params Kernel The kernel to finalize kernel arguments for. 673 void finalizeKernelArguments(ppcg_kernel *Kernel); 674 675 /// Create code that allocates memory to store arrays on device. 676 void allocateDeviceArrays(); 677 678 /// Create code to prepare the managed device pointers. 679 void prepareManagedDeviceArrays(); 680 681 /// Free all allocated device arrays. 682 void freeDeviceArrays(); 683 684 /// Create a call to initialize the GPU context. 685 /// 686 /// @returns A pointer to the newly initialized context. 687 Value *createCallInitContext(); 688 689 /// Create a call to get the device pointer for a kernel allocation. 690 /// 691 /// @param Allocation The Polly GPU allocation 692 /// 693 /// @returns The device parameter corresponding to this allocation. 694 Value *createCallGetDevicePtr(Value *Allocation); 695 696 /// Create a call to free the GPU context. 697 /// 698 /// @param Context A pointer to an initialized GPU context. 699 void createCallFreeContext(Value *Context); 700 701 /// Create a call to allocate memory on the device. 702 /// 703 /// @param Size The size of memory to allocate 704 /// 705 /// @returns A pointer that identifies this allocation. 706 Value *createCallAllocateMemoryForDevice(Value *Size); 707 708 /// Create a call to free a device array. 709 /// 710 /// @param Array The device array to free. 711 void createCallFreeDeviceMemory(Value *Array); 712 713 /// Create a call to copy data from host to device. 714 /// 715 /// @param HostPtr A pointer to the host data that should be copied. 716 /// @param DevicePtr A device pointer specifying the location to copy to. 717 void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 718 Value *Size); 719 720 /// Create a call to copy data from device to host. 721 /// 722 /// @param DevicePtr A pointer to the device data that should be copied. 723 /// @param HostPtr A host pointer specifying the location to copy to. 724 void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 725 Value *Size); 726 727 /// Create a call to synchronize Host & Device. 728 /// \note 729 /// This is to be used only with managed memory. 730 void createCallSynchronizeDevice(); 731 732 /// Create a call to get a kernel from an assembly string. 733 /// 734 /// @param Buffer The string describing the kernel. 735 /// @param Entry The name of the kernel function to call. 736 /// 737 /// @returns A pointer to a kernel object 738 Value *createCallGetKernel(Value *Buffer, Value *Entry); 739 740 /// Create a call to free a GPU kernel. 741 /// 742 /// @param GPUKernel THe kernel to free. 743 void createCallFreeKernel(Value *GPUKernel); 744 745 /// Create a call to launch a GPU kernel. 746 /// 747 /// @param GPUKernel The kernel to launch. 748 /// @param GridDimX The size of the first grid dimension. 749 /// @param GridDimY The size of the second grid dimension. 750 /// @param GridBlockX The size of the first block dimension. 751 /// @param GridBlockY The size of the second block dimension. 752 /// @param GridBlockZ The size of the third block dimension. 753 /// @param Parameters A pointer to an array that contains itself pointers to 754 /// the parameter values passed for each kernel argument. 755 void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 756 Value *GridDimY, Value *BlockDimX, 757 Value *BlockDimY, Value *BlockDimZ, 758 Value *Parameters); 759 }; 760 761 std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 762 return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 763 std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 764 } 765 766 void GPUNodeBuilder::initializeAfterRTH() { 767 BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 768 &*Builder.GetInsertPoint(), &DT, &LI); 769 NewBB->setName("polly.acc.initialize"); 770 Builder.SetInsertPoint(&NewBB->front()); 771 772 GPUContext = createCallInitContext(); 773 774 if (!PollyManagedMemory) 775 allocateDeviceArrays(); 776 else 777 prepareManagedDeviceArrays(); 778 } 779 780 void GPUNodeBuilder::finalize() { 781 if (!PollyManagedMemory) 782 freeDeviceArrays(); 783 784 createCallFreeContext(GPUContext); 785 IslNodeBuilder::finalize(); 786 } 787 788 void GPUNodeBuilder::allocateDeviceArrays() { 789 assert(!PollyManagedMemory && 790 "Managed memory will directly send host pointers " 791 "to the kernel. There is no need for device arrays"); 792 isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release()); 793 794 for (int i = 0; i < Prog->n_array; ++i) { 795 gpu_array_info *Array = &Prog->array[i]; 796 auto *ScopArray = (ScopArrayInfo *)Array->user; 797 std::string DevArrayName("p_dev_array_"); 798 DevArrayName.append(Array->name); 799 800 Value *ArraySize = getArraySize(Array); 801 Value *Offset = getArrayOffset(Array); 802 if (Offset) 803 ArraySize = Builder.CreateSub( 804 ArraySize, 805 Builder.CreateMul(Offset, 806 Builder.getInt64(ScopArray->getElemSizeInBytes()))); 807 const SCEV *SizeSCEV = SE.getSCEV(ArraySize); 808 // It makes no sense to have an array of size 0. The CUDA API will 809 // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We 810 // choose to be defensive and catch this at the compile phase. It is 811 // most likely that we are doing something wrong with size computation. 812 if (SizeSCEV->isZero()) { 813 errs() << getUniqueScopName(&S) 814 << " has computed array size 0: " << *ArraySize 815 << " | for array: " << *(ScopArray->getBasePtr()) 816 << ". This is illegal, exiting.\n"; 817 report_fatal_error("array size was computed to be 0"); 818 } 819 820 Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 821 DevArray->setName(DevArrayName); 822 DeviceAllocations[ScopArray] = DevArray; 823 } 824 825 isl_ast_build_free(Build); 826 } 827 828 void GPUNodeBuilder::prepareManagedDeviceArrays() { 829 assert(PollyManagedMemory && 830 "Device array most only be prepared in managed-memory mode"); 831 for (int i = 0; i < Prog->n_array; ++i) { 832 gpu_array_info *Array = &Prog->array[i]; 833 ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user; 834 Value *HostPtr; 835 836 if (gpu_array_is_scalar(Array)) 837 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 838 else 839 HostPtr = ScopArray->getBasePtr(); 840 HostPtr = getLatestValue(HostPtr); 841 842 Value *Offset = getArrayOffset(Array); 843 if (Offset) { 844 HostPtr = Builder.CreatePointerCast( 845 HostPtr, ScopArray->getElementType()->getPointerTo()); 846 HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset); 847 } 848 849 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 850 DeviceAllocations[ScopArray] = HostPtr; 851 } 852 } 853 854 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 855 Value *BlockDimY, Value *BlockDimZ) { 856 auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 857 858 for (auto &F : *M) { 859 if (F.getCallingConv() != CallingConv::PTX_Kernel) 860 continue; 861 862 Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 863 864 Metadata *Elements[] = { 865 ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 866 ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 867 ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 868 ValueAsMetadata::get(V[2]), 869 }; 870 MDNode *Node = MDNode::get(M->getContext(), Elements); 871 AnnotationNode->addOperand(Node); 872 } 873 } 874 875 void GPUNodeBuilder::freeDeviceArrays() { 876 assert(!PollyManagedMemory && "Managed memory does not use device arrays"); 877 for (auto &Array : DeviceAllocations) 878 createCallFreeDeviceMemory(Array.second); 879 } 880 881 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 882 const char *Name = "polly_getKernel"; 883 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 884 Function *F = M->getFunction(Name); 885 886 // If F is not available, declare it. 887 if (!F) { 888 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 889 std::vector<Type *> Args; 890 Args.push_back(Builder.getInt8PtrTy()); 891 Args.push_back(Builder.getInt8PtrTy()); 892 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 893 F = Function::Create(Ty, Linkage, Name, M); 894 } 895 896 return Builder.CreateCall(F, {Buffer, Entry}); 897 } 898 899 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 900 const char *Name = "polly_getDevicePtr"; 901 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 902 Function *F = M->getFunction(Name); 903 904 // If F is not available, declare it. 905 if (!F) { 906 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 907 std::vector<Type *> Args; 908 Args.push_back(Builder.getInt8PtrTy()); 909 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 910 F = Function::Create(Ty, Linkage, Name, M); 911 } 912 913 return Builder.CreateCall(F, {Allocation}); 914 } 915 916 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 917 Value *GridDimY, Value *BlockDimX, 918 Value *BlockDimY, Value *BlockDimZ, 919 Value *Parameters) { 920 const char *Name = "polly_launchKernel"; 921 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 922 Function *F = M->getFunction(Name); 923 924 // If F is not available, declare it. 925 if (!F) { 926 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 927 std::vector<Type *> Args; 928 Args.push_back(Builder.getInt8PtrTy()); 929 Args.push_back(Builder.getInt32Ty()); 930 Args.push_back(Builder.getInt32Ty()); 931 Args.push_back(Builder.getInt32Ty()); 932 Args.push_back(Builder.getInt32Ty()); 933 Args.push_back(Builder.getInt32Ty()); 934 Args.push_back(Builder.getInt8PtrTy()); 935 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 936 F = Function::Create(Ty, Linkage, Name, M); 937 } 938 939 Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 940 BlockDimZ, Parameters}); 941 } 942 943 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 944 const char *Name = "polly_freeKernel"; 945 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 946 Function *F = M->getFunction(Name); 947 948 // If F is not available, declare it. 949 if (!F) { 950 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 951 std::vector<Type *> Args; 952 Args.push_back(Builder.getInt8PtrTy()); 953 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 954 F = Function::Create(Ty, Linkage, Name, M); 955 } 956 957 Builder.CreateCall(F, {GPUKernel}); 958 } 959 960 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 961 assert(!PollyManagedMemory && 962 "Managed memory does not allocate or free memory " 963 "for device"); 964 const char *Name = "polly_freeDeviceMemory"; 965 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 966 Function *F = M->getFunction(Name); 967 968 // If F is not available, declare it. 969 if (!F) { 970 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 971 std::vector<Type *> Args; 972 Args.push_back(Builder.getInt8PtrTy()); 973 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 974 F = Function::Create(Ty, Linkage, Name, M); 975 } 976 977 Builder.CreateCall(F, {Array}); 978 } 979 980 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 981 assert(!PollyManagedMemory && 982 "Managed memory does not allocate or free memory " 983 "for device"); 984 const char *Name = "polly_allocateMemoryForDevice"; 985 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 986 Function *F = M->getFunction(Name); 987 988 // If F is not available, declare it. 989 if (!F) { 990 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 991 std::vector<Type *> Args; 992 Args.push_back(Builder.getInt64Ty()); 993 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 994 F = Function::Create(Ty, Linkage, Name, M); 995 } 996 997 return Builder.CreateCall(F, {Size}); 998 } 999 1000 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 1001 Value *DeviceData, 1002 Value *Size) { 1003 assert(!PollyManagedMemory && 1004 "Managed memory does not transfer memory between " 1005 "device and host"); 1006 const char *Name = "polly_copyFromHostToDevice"; 1007 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1008 Function *F = M->getFunction(Name); 1009 1010 // If F is not available, declare it. 1011 if (!F) { 1012 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1013 std::vector<Type *> Args; 1014 Args.push_back(Builder.getInt8PtrTy()); 1015 Args.push_back(Builder.getInt8PtrTy()); 1016 Args.push_back(Builder.getInt64Ty()); 1017 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1018 F = Function::Create(Ty, Linkage, Name, M); 1019 } 1020 1021 Builder.CreateCall(F, {HostData, DeviceData, Size}); 1022 } 1023 1024 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 1025 Value *HostData, 1026 Value *Size) { 1027 assert(!PollyManagedMemory && 1028 "Managed memory does not transfer memory between " 1029 "device and host"); 1030 const char *Name = "polly_copyFromDeviceToHost"; 1031 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1032 Function *F = M->getFunction(Name); 1033 1034 // If F is not available, declare it. 1035 if (!F) { 1036 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1037 std::vector<Type *> Args; 1038 Args.push_back(Builder.getInt8PtrTy()); 1039 Args.push_back(Builder.getInt8PtrTy()); 1040 Args.push_back(Builder.getInt64Ty()); 1041 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1042 F = Function::Create(Ty, Linkage, Name, M); 1043 } 1044 1045 Builder.CreateCall(F, {DeviceData, HostData, Size}); 1046 } 1047 1048 void GPUNodeBuilder::createCallSynchronizeDevice() { 1049 assert(PollyManagedMemory && "explicit synchronization is only necessary for " 1050 "managed memory"); 1051 const char *Name = "polly_synchronizeDevice"; 1052 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1053 Function *F = M->getFunction(Name); 1054 1055 // If F is not available, declare it. 1056 if (!F) { 1057 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1058 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 1059 F = Function::Create(Ty, Linkage, Name, M); 1060 } 1061 1062 Builder.CreateCall(F); 1063 } 1064 1065 Value *GPUNodeBuilder::createCallInitContext() { 1066 const char *Name; 1067 1068 switch (Runtime) { 1069 case GPURuntime::CUDA: 1070 Name = "polly_initContextCUDA"; 1071 break; 1072 case GPURuntime::OpenCL: 1073 Name = "polly_initContextCL"; 1074 break; 1075 } 1076 1077 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1078 Function *F = M->getFunction(Name); 1079 1080 // If F is not available, declare it. 1081 if (!F) { 1082 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1083 std::vector<Type *> Args; 1084 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 1085 F = Function::Create(Ty, Linkage, Name, M); 1086 } 1087 1088 return Builder.CreateCall(F, {}); 1089 } 1090 1091 void GPUNodeBuilder::createCallFreeContext(Value *Context) { 1092 const char *Name = "polly_freeContext"; 1093 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1094 Function *F = M->getFunction(Name); 1095 1096 // If F is not available, declare it. 1097 if (!F) { 1098 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1099 std::vector<Type *> Args; 1100 Args.push_back(Builder.getInt8PtrTy()); 1101 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1102 F = Function::Create(Ty, Linkage, Name, M); 1103 } 1104 1105 Builder.CreateCall(F, {Context}); 1106 } 1107 1108 /// Check if one string is a prefix of another. 1109 /// 1110 /// @param String The string in which to look for the prefix. 1111 /// @param Prefix The prefix to look for. 1112 static bool isPrefix(std::string String, std::string Prefix) { 1113 return String.find(Prefix) == 0; 1114 } 1115 1116 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1117 isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1118 Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 1119 1120 if (!gpu_array_is_scalar(Array)) { 1121 isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound); 1122 1123 isl::pw_aff OffsetDimZero = ArrayBound.at(0); 1124 isl::ast_expr Res = Build.expr_from(OffsetDimZero); 1125 1126 for (unsigned int i = 1; i < Array->n_index; i++) { 1127 isl::pw_aff Bound_I = ArrayBound.at(i); 1128 isl::ast_expr Expr = Build.expr_from(Bound_I); 1129 Res = Res.mul(Expr); 1130 } 1131 1132 Value *NumElements = ExprBuilder.create(Res.release()); 1133 if (NumElements->getType() != ArraySize->getType()) 1134 NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 1135 ArraySize = Builder.CreateMul(ArraySize, NumElements); 1136 } 1137 return ArraySize; 1138 } 1139 1140 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1141 if (gpu_array_is_scalar(Array)) 1142 return nullptr; 1143 1144 isl::ast_build Build = isl::ast_build::from_context(S.getContext()); 1145 1146 isl::set Min = isl::manage_copy(Array->extent).lexmin(); 1147 1148 isl::set ZeroSet = isl::set::universe(Min.get_space()); 1149 1150 for (unsigned i : rangeIslSize(0, Min.tuple_dim())) 1151 ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1152 1153 if (Min.is_subset(ZeroSet)) { 1154 return nullptr; 1155 } 1156 1157 isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.ctx(), 0)); 1158 1159 for (unsigned i : rangeIslSize(0, Min.tuple_dim())) { 1160 if (i > 0) { 1161 isl::pw_aff Bound_I = 1162 isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1163 isl::ast_expr BExpr = Build.expr_from(Bound_I); 1164 Result = Result.mul(BExpr); 1165 } 1166 isl::pw_aff DimMin = Min.dim_min(i); 1167 isl::ast_expr MExpr = Build.expr_from(DimMin); 1168 Result = Result.add(MExpr); 1169 } 1170 1171 return ExprBuilder.create(Result.release()); 1172 } 1173 1174 Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1175 ScopArrayInfo *ArrayInfo) { 1176 assert(PollyManagedMemory && "Only used when you wish to get a host " 1177 "pointer for sending data to the kernel, " 1178 "with managed memory"); 1179 std::map<ScopArrayInfo *, Value *>::iterator it; 1180 it = DeviceAllocations.find(ArrayInfo); 1181 assert(it != DeviceAllocations.end() && 1182 "Device array expected to be available"); 1183 return it->second; 1184 } 1185 1186 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 1187 enum DataDirection Direction) { 1188 assert(!PollyManagedMemory && "Managed memory needs no data transfers"); 1189 isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 1190 isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 1191 isl_id *Id = isl_ast_expr_get_id(Arg); 1192 auto Array = (gpu_array_info *)isl_id_get_user(Id); 1193 auto ScopArray = (ScopArrayInfo *)(Array->user); 1194 1195 Value *Size = getArraySize(Array); 1196 Value *Offset = getArrayOffset(Array); 1197 Value *DevPtr = DeviceAllocations[ScopArray]; 1198 1199 Value *HostPtr; 1200 1201 if (gpu_array_is_scalar(Array)) 1202 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1203 else 1204 HostPtr = ScopArray->getBasePtr(); 1205 HostPtr = getLatestValue(HostPtr); 1206 1207 if (Offset) { 1208 HostPtr = Builder.CreatePointerCast( 1209 HostPtr, ScopArray->getElementType()->getPointerTo()); 1210 HostPtr = Builder.CreateGEP(ScopArray->getElementType(), HostPtr, Offset); 1211 } 1212 1213 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1214 1215 if (Offset) { 1216 Size = Builder.CreateSub( 1217 Size, Builder.CreateMul( 1218 Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1219 } 1220 1221 if (Direction == HOST_TO_DEVICE) 1222 createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 1223 else 1224 createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 1225 1226 isl_id_free(Id); 1227 isl_ast_expr_free(Arg); 1228 isl_ast_expr_free(Expr); 1229 isl_ast_node_free(TransferStmt); 1230 } 1231 1232 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 1233 isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 1234 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1235 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1236 isl_id_free(Id); 1237 isl_ast_expr_free(StmtExpr); 1238 1239 const char *Str = isl_id_get_name(Id); 1240 if (!strcmp(Str, "kernel")) { 1241 createKernel(UserStmt); 1242 if (PollyManagedMemory) 1243 createCallSynchronizeDevice(); 1244 isl_ast_expr_free(Expr); 1245 return; 1246 } 1247 if (!strcmp(Str, "init_device")) { 1248 initializeAfterRTH(); 1249 isl_ast_node_free(UserStmt); 1250 isl_ast_expr_free(Expr); 1251 return; 1252 } 1253 if (!strcmp(Str, "clear_device")) { 1254 finalize(); 1255 isl_ast_node_free(UserStmt); 1256 isl_ast_expr_free(Expr); 1257 return; 1258 } 1259 if (isPrefix(Str, "to_device")) { 1260 if (!PollyManagedMemory) 1261 createDataTransfer(UserStmt, HOST_TO_DEVICE); 1262 else 1263 isl_ast_node_free(UserStmt); 1264 1265 isl_ast_expr_free(Expr); 1266 return; 1267 } 1268 1269 if (isPrefix(Str, "from_device")) { 1270 if (!PollyManagedMemory) { 1271 createDataTransfer(UserStmt, DEVICE_TO_HOST); 1272 } else { 1273 isl_ast_node_free(UserStmt); 1274 } 1275 isl_ast_expr_free(Expr); 1276 return; 1277 } 1278 1279 isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 1280 struct ppcg_kernel_stmt *KernelStmt = 1281 (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 1282 isl_id_free(Anno); 1283 1284 switch (KernelStmt->type) { 1285 case ppcg_kernel_domain: 1286 createScopStmt(Expr, KernelStmt); 1287 isl_ast_node_free(UserStmt); 1288 return; 1289 case ppcg_kernel_copy: 1290 createKernelCopy(KernelStmt); 1291 isl_ast_expr_free(Expr); 1292 isl_ast_node_free(UserStmt); 1293 return; 1294 case ppcg_kernel_sync: 1295 createKernelSync(); 1296 isl_ast_expr_free(Expr); 1297 isl_ast_node_free(UserStmt); 1298 return; 1299 } 1300 1301 isl_ast_expr_free(Expr); 1302 isl_ast_node_free(UserStmt); 1303 } 1304 1305 void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) { 1306 createForSequential(isl::manage(Node).as<isl::ast_node_for>(), false); 1307 } 1308 1309 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1310 isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1311 auto LocalAddr = ExprBuilder.createAccessAddress(LocalIndex); 1312 isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1313 auto GlobalAddr = ExprBuilder.createAccessAddress(Index); 1314 1315 if (KernelStmt->u.c.read) { 1316 LoadInst *Load = 1317 Builder.CreateLoad(GlobalAddr.second, GlobalAddr.first, "shared.read"); 1318 Builder.CreateStore(Load, LocalAddr.first); 1319 } else { 1320 LoadInst *Load = 1321 Builder.CreateLoad(LocalAddr.second, LocalAddr.first, "shared.write"); 1322 Builder.CreateStore(Load, GlobalAddr.first); 1323 } 1324 } 1325 1326 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1327 ppcg_kernel_stmt *KernelStmt) { 1328 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1329 isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1330 1331 LoopToScevMapT LTS; 1332 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1333 1334 createSubstitutions(Expr, Stmt, LTS); 1335 1336 if (Stmt->isBlockStmt()) 1337 BlockGen.copyStmt(*Stmt, LTS, Indexes); 1338 else 1339 RegionGen.copyStmt(*Stmt, LTS, Indexes); 1340 } 1341 1342 void GPUNodeBuilder::createKernelSync() { 1343 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1344 const char *SpirName = "__gen_ocl_barrier_global"; 1345 1346 Function *Sync; 1347 1348 switch (Arch) { 1349 case GPUArch::SPIR64: 1350 case GPUArch::SPIR32: 1351 Sync = M->getFunction(SpirName); 1352 1353 // If Sync is not available, declare it. 1354 if (!Sync) { 1355 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1356 std::vector<Type *> Args; 1357 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1358 Sync = Function::Create(Ty, Linkage, SpirName, M); 1359 Sync->setCallingConv(CallingConv::SPIR_FUNC); 1360 } 1361 break; 1362 case GPUArch::NVPTX64: 1363 Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 1364 break; 1365 } 1366 1367 Builder.CreateCall(Sync, {}); 1368 } 1369 1370 /// Collect llvm::Values referenced from @p Node 1371 /// 1372 /// This function only applies to isl_ast_nodes that are user_nodes referring 1373 /// to a ScopStmt. All other node types are ignore. 1374 /// 1375 /// @param Node The node to collect references for. 1376 /// @param User A user pointer used as storage for the data that is collected. 1377 /// 1378 /// @returns isl_bool_true if data could be collected successfully. 1379 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1380 if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1381 return isl_bool_true; 1382 1383 isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1384 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1385 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1386 const char *Str = isl_id_get_name(Id); 1387 isl_id_free(Id); 1388 isl_ast_expr_free(StmtExpr); 1389 isl_ast_expr_free(Expr); 1390 1391 if (!isPrefix(Str, "Stmt")) 1392 return isl_bool_true; 1393 1394 Id = isl_ast_node_get_annotation(Node); 1395 auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1396 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1397 isl_id_free(Id); 1398 1399 addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1400 1401 return isl_bool_true; 1402 } 1403 1404 /// A list of functions that are available in NVIDIA's libdevice. 1405 const std::set<std::string> CUDALibDeviceFunctions = { 1406 "exp", "expf", "expl", "cos", "cosf", "sqrt", "sqrtf", 1407 "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"}; 1408 1409 // A map from intrinsics to their corresponding libdevice functions. 1410 const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = { 1411 {"llvm.exp.f64", "exp"}, 1412 {"llvm.exp.f32", "expf"}, 1413 {"llvm.powi.f64.i32", "powi"}, 1414 {"llvm.powi.f32.i32", "powif"}}; 1415 1416 /// Return the corresponding CUDA libdevice function name @p Name. 1417 /// Note that this function will try to convert instrinsics in the list 1418 /// IntrinsicToLibdeviceFunc into libdevice functions. 1419 /// This is because some intrinsics such as `exp` 1420 /// are not supported by the NVPTX backend. 1421 /// If this restriction of the backend is lifted, we should refactor our code 1422 /// so that we use intrinsics whenever possible. 1423 /// 1424 /// Return "" if we are not compiling for CUDA. 1425 std::string getCUDALibDeviceFuntion(StringRef NameRef) { 1426 std::string Name = NameRef.str(); 1427 auto It = IntrinsicToLibdeviceFunc.find(Name); 1428 if (It != IntrinsicToLibdeviceFunc.end()) 1429 return getCUDALibDeviceFuntion(It->second); 1430 1431 if (CUDALibDeviceFunctions.count(Name)) 1432 return ("__nv_" + Name); 1433 1434 return ""; 1435 } 1436 1437 /// Check if F is a function that we can code-generate in a GPU kernel. 1438 static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1439 assert(F && "F is an invalid pointer"); 1440 // We string compare against the name of the function to allow 1441 // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 1442 // "llvm.copysign". 1443 const StringRef Name = F->getName(); 1444 1445 if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0) 1446 return true; 1447 1448 return F->isIntrinsic() && 1449 (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 1450 Name.startswith("llvm.copysign")); 1451 } 1452 1453 /// Do not take `Function` as a subtree value. 1454 /// 1455 /// We try to take the reference of all subtree values and pass them along 1456 /// to the kernel from the host. Taking an address of any function and 1457 /// trying to pass along is nonsensical. Only allow `Value`s that are not 1458 /// `Function`s. 1459 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1460 1461 /// Return `Function`s from `RawSubtreeValues`. 1462 static SetVector<Function *> 1463 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 1464 bool AllowCUDALibDevice) { 1465 SetVector<Function *> SubtreeFunctions; 1466 for (Value *It : RawSubtreeValues) { 1467 Function *F = dyn_cast<Function>(It); 1468 if (F) { 1469 assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 1470 "Code should have bailed out by " 1471 "this point if an invalid function " 1472 "were present in a kernel."); 1473 SubtreeFunctions.insert(F); 1474 } 1475 } 1476 return SubtreeFunctions; 1477 } 1478 1479 std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>, 1480 isl::space> 1481 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1482 SetVector<Value *> SubtreeValues; 1483 SetVector<const SCEV *> SCEVs; 1484 SetVector<const Loop *> Loops; 1485 isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params(); 1486 SubtreeReferences References = { 1487 LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(), 1488 &ParamSpace}; 1489 1490 for (const auto &I : IDToValue) 1491 SubtreeValues.insert(I.second); 1492 1493 // NOTE: this is populated in IslNodeBuilder::addParameters 1494 // See [Code generation of induction variables of loops outside Scops]. 1495 for (const auto &I : OutsideLoopIterations) 1496 SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1497 1498 isl_ast_node_foreach_descendant_top_down( 1499 Kernel->tree, collectReferencesInGPUStmt, &References); 1500 1501 for (const SCEV *Expr : SCEVs) { 1502 findValues(Expr, SE, SubtreeValues); 1503 findLoops(Expr, Loops); 1504 } 1505 1506 Loops.remove_if([this](const Loop *L) { 1507 return S.contains(L) || L->contains(S.getEntry()); 1508 }); 1509 1510 for (auto &SAI : S.arrays()) 1511 SubtreeValues.remove(SAI->getBasePtr()); 1512 1513 isl_space *Space = S.getParamSpace().release(); 1514 for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) { 1515 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1516 assert(IDToValue.count(Id)); 1517 Value *Val = IDToValue[Id]; 1518 SubtreeValues.remove(Val); 1519 isl_id_free(Id); 1520 } 1521 isl_space_free(Space); 1522 1523 for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) { 1524 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1525 assert(IDToValue.count(Id)); 1526 Value *Val = IDToValue[Id]; 1527 SubtreeValues.remove(Val); 1528 isl_id_free(Id); 1529 } 1530 1531 // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1532 // SubtreeValues. This is important, because we should not lose any 1533 // SubtreeValues in the process of constructing the 1534 // "ValidSubtree{Values, Functions} sets. Nor should the set 1535 // ValidSubtree{Values, Functions} have any common element. 1536 auto ValidSubtreeValuesIt = 1537 make_filter_range(SubtreeValues, isValidSubtreeValue); 1538 SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1539 ValidSubtreeValuesIt.end()); 1540 1541 bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 1542 1543 SetVector<Function *> ValidSubtreeFunctions( 1544 getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1545 1546 // @see IslNodeBuilder::getReferencesInSubtree 1547 SetVector<Value *> ReplacedValues; 1548 for (Value *V : ValidSubtreeValues) { 1549 auto It = ValueMap.find(V); 1550 if (It == ValueMap.end()) 1551 ReplacedValues.insert(V); 1552 else 1553 ReplacedValues.insert(It->second); 1554 } 1555 return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops, 1556 ParamSpace); 1557 } 1558 1559 void GPUNodeBuilder::clearDominators(Function *F) { 1560 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 1561 std::vector<BasicBlock *> Nodes; 1562 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 1563 Nodes.push_back(I->getBlock()); 1564 1565 for (BasicBlock *BB : Nodes) 1566 DT.eraseNode(BB); 1567 } 1568 1569 void GPUNodeBuilder::clearScalarEvolution(Function *F) { 1570 for (BasicBlock &BB : *F) { 1571 Loop *L = LI.getLoopFor(&BB); 1572 if (L) 1573 SE.forgetLoop(L); 1574 } 1575 } 1576 1577 void GPUNodeBuilder::clearLoops(Function *F) { 1578 SmallSet<Loop *, 1> WorkList; 1579 for (BasicBlock &BB : *F) { 1580 Loop *L = LI.getLoopFor(&BB); 1581 if (L) 1582 WorkList.insert(L); 1583 } 1584 for (auto *L : WorkList) 1585 LI.erase(L); 1586 } 1587 1588 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 1589 std::vector<Value *> Sizes; 1590 isl::ast_build Context = isl::ast_build::from_context(S.getContext()); 1591 1592 isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size); 1593 for (long i = 0; i < Kernel->n_grid; i++) { 1594 isl::pw_aff Size = GridSizePwAffs.at(i); 1595 isl::ast_expr GridSize = Context.expr_from(Size); 1596 Value *Res = ExprBuilder.create(GridSize.release()); 1597 Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 1598 Sizes.push_back(Res); 1599 } 1600 1601 for (long i = Kernel->n_grid; i < 3; i++) 1602 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1603 1604 return std::make_tuple(Sizes[0], Sizes[1]); 1605 } 1606 1607 std::tuple<Value *, Value *, Value *> 1608 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 1609 std::vector<Value *> Sizes; 1610 1611 for (long i = 0; i < Kernel->n_block; i++) { 1612 Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 1613 Sizes.push_back(Res); 1614 } 1615 1616 for (long i = Kernel->n_block; i < 3; i++) 1617 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1618 1619 return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 1620 } 1621 1622 void GPUNodeBuilder::insertStoreParameter(Type *ArrayTy, 1623 Instruction *Parameters, 1624 Instruction *Param, int Index) { 1625 Value *Slot = Builder.CreateGEP( 1626 ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1627 Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1628 Builder.CreateStore(ParamTyped, Slot); 1629 } 1630 1631 Value * 1632 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 1633 SetVector<Value *> SubtreeValues) { 1634 const int NumArgs = F->arg_size(); 1635 std::vector<int> ArgSizes(NumArgs); 1636 1637 // If we are using the OpenCL Runtime, we need to add the kernel argument 1638 // sizes to the end of the launch-parameter list, so OpenCL can determine 1639 // how big the respective kernel arguments are. 1640 // Here we need to reserve adequate space for that. 1641 Type *ArrayTy; 1642 if (Runtime == GPURuntime::OpenCL) 1643 ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 1644 else 1645 ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs); 1646 1647 BasicBlock *EntryBlock = 1648 &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1649 auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 1650 std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 1651 Instruction *Parameters = new AllocaInst( 1652 ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 1653 1654 int Index = 0; 1655 for (long i = 0; i < Prog->n_array; i++) { 1656 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1657 continue; 1658 1659 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1660 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1661 1662 if (Runtime == GPURuntime::OpenCL) 1663 ArgSizes[Index] = SAI->getElemSizeInBytes(); 1664 1665 Value *DevArray = nullptr; 1666 if (PollyManagedMemory) { 1667 DevArray = getManagedDeviceArray(&Prog->array[i], 1668 const_cast<ScopArrayInfo *>(SAI)); 1669 } else { 1670 DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 1671 DevArray = createCallGetDevicePtr(DevArray); 1672 } 1673 assert(DevArray != nullptr && "Array to be offloaded to device not " 1674 "initialized"); 1675 Value *Offset = getArrayOffset(&Prog->array[i]); 1676 1677 if (Offset) { 1678 DevArray = Builder.CreatePointerCast( 1679 DevArray, SAI->getElementType()->getPointerTo()); 1680 DevArray = Builder.CreateGEP(SAI->getElementType(), DevArray, 1681 Builder.CreateNeg(Offset)); 1682 DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1683 } 1684 Value *Slot = Builder.CreateGEP( 1685 ArrayTy, Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1686 1687 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1688 Value *ValPtr = nullptr; 1689 if (PollyManagedMemory) 1690 ValPtr = DevArray; 1691 else 1692 ValPtr = BlockGen.getOrCreateAlloca(SAI); 1693 1694 assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1695 " to be stored into Parameters"); 1696 Value *ValPtrCast = 1697 Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1698 Builder.CreateStore(ValPtrCast, Slot); 1699 } else { 1700 Instruction *Param = 1701 new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 1702 Launch + "_param_" + std::to_string(Index), 1703 EntryBlock->getTerminator()); 1704 Builder.CreateStore(DevArray, Param); 1705 Value *ParamTyped = 1706 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1707 Builder.CreateStore(ParamTyped, Slot); 1708 } 1709 Index++; 1710 } 1711 1712 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1713 1714 for (long i = 0; i < NumHostIters; i++) { 1715 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1716 Value *Val = IDToValue[Id]; 1717 isl_id_free(Id); 1718 1719 if (Runtime == GPURuntime::OpenCL) 1720 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1721 1722 Instruction *Param = 1723 new AllocaInst(Val->getType(), AddressSpace, 1724 Launch + "_param_" + std::to_string(Index), 1725 EntryBlock->getTerminator()); 1726 Builder.CreateStore(Val, Param); 1727 insertStoreParameter(ArrayTy, Parameters, Param, Index); 1728 Index++; 1729 } 1730 1731 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1732 1733 for (long i = 0; i < NumVars; i++) { 1734 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1735 Value *Val = IDToValue[Id]; 1736 if (ValueMap.count(Val)) 1737 Val = ValueMap[Val]; 1738 isl_id_free(Id); 1739 1740 if (Runtime == GPURuntime::OpenCL) 1741 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1742 1743 Instruction *Param = 1744 new AllocaInst(Val->getType(), AddressSpace, 1745 Launch + "_param_" + std::to_string(Index), 1746 EntryBlock->getTerminator()); 1747 Builder.CreateStore(Val, Param); 1748 insertStoreParameter(ArrayTy, Parameters, Param, Index); 1749 Index++; 1750 } 1751 1752 for (auto Val : SubtreeValues) { 1753 if (Runtime == GPURuntime::OpenCL) 1754 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1755 1756 Instruction *Param = 1757 new AllocaInst(Val->getType(), AddressSpace, 1758 Launch + "_param_" + std::to_string(Index), 1759 EntryBlock->getTerminator()); 1760 Builder.CreateStore(Val, Param); 1761 insertStoreParameter(ArrayTy, Parameters, Param, Index); 1762 Index++; 1763 } 1764 1765 if (Runtime == GPURuntime::OpenCL) { 1766 for (int i = 0; i < NumArgs; i++) { 1767 Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1768 Instruction *Param = 1769 new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1770 Launch + "_param_size_" + std::to_string(i), 1771 EntryBlock->getTerminator()); 1772 Builder.CreateStore(Val, Param); 1773 insertStoreParameter(ArrayTy, Parameters, Param, Index); 1774 Index++; 1775 } 1776 } 1777 1778 auto Location = EntryBlock->getTerminator(); 1779 return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 1780 Launch + "_params_i8ptr", Location); 1781 } 1782 1783 void GPUNodeBuilder::setupKernelSubtreeFunctions( 1784 SetVector<Function *> SubtreeFunctions) { 1785 for (auto Fn : SubtreeFunctions) { 1786 const std::string ClonedFnName = Fn->getName().str(); 1787 Function *Clone = GPUModule->getFunction(ClonedFnName); 1788 if (!Clone) 1789 Clone = 1790 Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1791 ClonedFnName, GPUModule.get()); 1792 assert(Clone && "Expected cloned function to be initialized."); 1793 assert(ValueMap.find(Fn) == ValueMap.end() && 1794 "Fn already present in ValueMap"); 1795 ValueMap[Fn] = Clone; 1796 } 1797 } 1798 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 1799 isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 1800 ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 1801 isl_id_free(Id); 1802 isl_ast_node_free(KernelStmt); 1803 1804 if (Kernel->n_grid > 1) 1805 DeepestParallel = std::max( 1806 DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set)); 1807 else 1808 DeepestSequential = std::max( 1809 DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set)); 1810 1811 Value *BlockDimX, *BlockDimY, *BlockDimZ; 1812 std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1813 1814 SetVector<Value *> SubtreeValues; 1815 SetVector<Function *> SubtreeFunctions; 1816 SetVector<const Loop *> Loops; 1817 isl::space ParamSpace; 1818 std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) = 1819 getReferencesInKernel(Kernel); 1820 1821 // Add parameters that appear only in the access function to the kernel 1822 // space. This is important to make sure that all isl_ids are passed as 1823 // parameters to the kernel, even though we may not have all parameters 1824 // in the context to improve compile time. 1825 Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release()); 1826 1827 assert(Kernel->tree && "Device AST of kernel node is empty"); 1828 1829 Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1830 IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1831 ValueMapT HostValueMap = ValueMap; 1832 BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1833 ScalarMap.clear(); 1834 BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap; 1835 EscapeMap.clear(); 1836 1837 // Create for all loops we depend on values that contain the current loop 1838 // iteration. These values are necessary to generate code for SCEVs that 1839 // depend on such loops. As a result we need to pass them to the subfunction. 1840 for (const Loop *L : Loops) { 1841 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1842 SE.getUnknown(Builder.getInt64(1)), 1843 L, SCEV::FlagAnyWrap); 1844 Value *V = generateSCEV(OuterLIV); 1845 OutsideLoopIterations[L] = SE.getUnknown(V); 1846 SubtreeValues.insert(V); 1847 } 1848 1849 createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1850 setupKernelSubtreeFunctions(SubtreeFunctions); 1851 1852 create(isl_ast_node_copy(Kernel->tree)); 1853 1854 finalizeKernelArguments(Kernel); 1855 Function *F = Builder.GetInsertBlock()->getParent(); 1856 if (Arch == GPUArch::NVPTX64) 1857 addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 1858 clearDominators(F); 1859 clearScalarEvolution(F); 1860 clearLoops(F); 1861 1862 IDToValue = HostIDs; 1863 1864 ValueMap = std::move(HostValueMap); 1865 ScalarMap = std::move(HostScalarMap); 1866 EscapeMap = std::move(HostEscapeMap); 1867 IDToSAI.clear(); 1868 Annotator.resetAlternativeAliasBases(); 1869 for (auto &BasePtr : LocalArrays) 1870 S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 1871 LocalArrays.clear(); 1872 1873 std::string ASMString = finalizeKernelFunction(); 1874 Builder.SetInsertPoint(&HostInsertPoint); 1875 Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 1876 1877 std::string Name = getKernelFuncName(Kernel->id); 1878 Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 1879 Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 1880 Value *GPUKernel = createCallGetKernel(KernelString, NameString); 1881 1882 Value *GridDimX, *GridDimY; 1883 std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 1884 1885 createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 1886 BlockDimZ, Parameters); 1887 createCallFreeKernel(GPUKernel); 1888 1889 for (auto Id : KernelIds) 1890 isl_id_free(Id); 1891 1892 KernelIds.clear(); 1893 } 1894 1895 /// Compute the DataLayout string for the NVPTX backend. 1896 /// 1897 /// @param is64Bit Are we looking for a 64 bit architecture? 1898 static std::string computeNVPTXDataLayout(bool is64Bit) { 1899 std::string Ret = ""; 1900 1901 if (!is64Bit) { 1902 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1903 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1904 "64-v128:128:128-n16:32:64"; 1905 } else { 1906 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1907 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1908 "64-v128:128:128-n16:32:64"; 1909 } 1910 1911 return Ret; 1912 } 1913 1914 /// Compute the DataLayout string for a SPIR kernel. 1915 /// 1916 /// @param is64Bit Are we looking for a 64 bit architecture? 1917 static std::string computeSPIRDataLayout(bool is64Bit) { 1918 std::string Ret = ""; 1919 1920 if (!is64Bit) { 1921 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1922 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1923 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1924 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1925 } else { 1926 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1927 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1928 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1929 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1930 } 1931 1932 return Ret; 1933 } 1934 1935 Function * 1936 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1937 SetVector<Value *> &SubtreeValues) { 1938 std::vector<Type *> Args; 1939 std::string Identifier = getKernelFuncName(Kernel->id); 1940 1941 std::vector<Metadata *> MemoryType; 1942 1943 for (long i = 0; i < Prog->n_array; i++) { 1944 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1945 continue; 1946 1947 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1948 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1949 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1950 Args.push_back(SAI->getElementType()); 1951 MemoryType.push_back( 1952 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1953 } else { 1954 static const int UseGlobalMemory = 1; 1955 Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 1956 MemoryType.push_back( 1957 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 1958 } 1959 } 1960 1961 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1962 1963 for (long i = 0; i < NumHostIters; i++) { 1964 Args.push_back(Builder.getInt64Ty()); 1965 MemoryType.push_back( 1966 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1967 } 1968 1969 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1970 1971 for (long i = 0; i < NumVars; i++) { 1972 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1973 Value *Val = IDToValue[Id]; 1974 isl_id_free(Id); 1975 Args.push_back(Val->getType()); 1976 MemoryType.push_back( 1977 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1978 } 1979 1980 for (auto *V : SubtreeValues) { 1981 Args.push_back(V->getType()); 1982 MemoryType.push_back( 1983 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1984 } 1985 1986 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1987 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1988 GPUModule.get()); 1989 1990 std::vector<Metadata *> EmptyStrings; 1991 1992 for (unsigned int i = 0; i < MemoryType.size(); i++) { 1993 EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 1994 } 1995 1996 if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 1997 FN->setMetadata("kernel_arg_addr_space", 1998 MDNode::get(FN->getContext(), MemoryType)); 1999 FN->setMetadata("kernel_arg_name", 2000 MDNode::get(FN->getContext(), EmptyStrings)); 2001 FN->setMetadata("kernel_arg_access_qual", 2002 MDNode::get(FN->getContext(), EmptyStrings)); 2003 FN->setMetadata("kernel_arg_type", 2004 MDNode::get(FN->getContext(), EmptyStrings)); 2005 FN->setMetadata("kernel_arg_type_qual", 2006 MDNode::get(FN->getContext(), EmptyStrings)); 2007 FN->setMetadata("kernel_arg_base_type", 2008 MDNode::get(FN->getContext(), EmptyStrings)); 2009 } 2010 2011 switch (Arch) { 2012 case GPUArch::NVPTX64: 2013 FN->setCallingConv(CallingConv::PTX_Kernel); 2014 break; 2015 case GPUArch::SPIR32: 2016 case GPUArch::SPIR64: 2017 FN->setCallingConv(CallingConv::SPIR_KERNEL); 2018 break; 2019 } 2020 2021 auto Arg = FN->arg_begin(); 2022 for (long i = 0; i < Kernel->n_array; i++) { 2023 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2024 continue; 2025 2026 Arg->setName(Kernel->array[i].array->name); 2027 2028 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2029 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 2030 Type *EleTy = SAI->getElementType(); 2031 Value *Val = &*Arg; 2032 SmallVector<const SCEV *, 4> Sizes; 2033 isl_ast_build *Build = 2034 isl_ast_build_from_context(isl_set_copy(Prog->context)); 2035 Sizes.push_back(nullptr); 2036 for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) { 2037 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 2038 Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 2039 auto V = ExprBuilder.create(DimSize); 2040 Sizes.push_back(SE.getSCEV(V)); 2041 } 2042 const ScopArrayInfo *SAIRep = 2043 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 2044 LocalArrays.push_back(Val); 2045 2046 isl_ast_build_free(Build); 2047 KernelIds.push_back(Id); 2048 IDToSAI[Id] = SAIRep; 2049 Arg++; 2050 } 2051 2052 for (long i = 0; i < NumHostIters; i++) { 2053 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 2054 Arg->setName(isl_id_get_name(Id)); 2055 IDToValue[Id] = &*Arg; 2056 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2057 Arg++; 2058 } 2059 2060 for (long i = 0; i < NumVars; i++) { 2061 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 2062 Arg->setName(isl_id_get_name(Id)); 2063 Value *Val = IDToValue[Id]; 2064 ValueMap[Val] = &*Arg; 2065 IDToValue[Id] = &*Arg; 2066 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2067 Arg++; 2068 } 2069 2070 for (auto *V : SubtreeValues) { 2071 Arg->setName(V->getName()); 2072 ValueMap[V] = &*Arg; 2073 Arg++; 2074 } 2075 2076 return FN; 2077 } 2078 2079 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 2080 Intrinsic::ID IntrinsicsBID[2]; 2081 Intrinsic::ID IntrinsicsTID[3]; 2082 2083 switch (Arch) { 2084 case GPUArch::SPIR64: 2085 case GPUArch::SPIR32: 2086 llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 2087 case GPUArch::NVPTX64: 2088 IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 2089 IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 2090 2091 IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 2092 IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 2093 IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 2094 break; 2095 } 2096 2097 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2098 std::string Name = isl_id_get_name(Id); 2099 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2100 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2101 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2102 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2103 IDToValue[Id] = Val; 2104 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2105 }; 2106 2107 for (int i = 0; i < Kernel->n_grid; ++i) { 2108 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2109 addId(Id, IntrinsicsBID[i]); 2110 } 2111 2112 for (int i = 0; i < Kernel->n_block; ++i) { 2113 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2114 addId(Id, IntrinsicsTID[i]); 2115 } 2116 } 2117 2118 void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel, 2119 bool SizeTypeIs64bit) { 2120 const char *GroupName[3] = {"__gen_ocl_get_group_id0", 2121 "__gen_ocl_get_group_id1", 2122 "__gen_ocl_get_group_id2"}; 2123 2124 const char *LocalName[3] = {"__gen_ocl_get_local_id0", 2125 "__gen_ocl_get_local_id1", 2126 "__gen_ocl_get_local_id2"}; 2127 IntegerType *SizeT = 2128 SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty(); 2129 2130 auto createFunc = [this](const char *Name, __isl_take isl_id *Id, 2131 IntegerType *SizeT) mutable { 2132 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2133 Function *FN = M->getFunction(Name); 2134 2135 // If FN is not available, declare it. 2136 if (!FN) { 2137 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 2138 std::vector<Type *> Args; 2139 FunctionType *Ty = FunctionType::get(SizeT, Args, false); 2140 FN = Function::Create(Ty, Linkage, Name, M); 2141 FN->setCallingConv(CallingConv::SPIR_FUNC); 2142 } 2143 2144 Value *Val = Builder.CreateCall(FN, {}); 2145 if (SizeT == Builder.getInt32Ty()) 2146 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2147 IDToValue[Id] = Val; 2148 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2149 }; 2150 2151 for (int i = 0; i < Kernel->n_grid; ++i) 2152 createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT); 2153 2154 for (int i = 0; i < Kernel->n_block; ++i) 2155 createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT); 2156 } 2157 2158 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 2159 auto Arg = FN->arg_begin(); 2160 for (long i = 0; i < Kernel->n_array; i++) { 2161 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2162 continue; 2163 2164 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2165 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 2166 isl_id_free(Id); 2167 2168 if (SAI->getNumberOfDimensions() > 0) { 2169 Arg++; 2170 continue; 2171 } 2172 2173 Value *Val = &*Arg; 2174 2175 if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 2176 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2177 Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2178 Val = Builder.CreateLoad(SAI->getElementType(), TypedArgPtr); 2179 } 2180 2181 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2182 Builder.CreateStore(Val, Alloca); 2183 2184 Arg++; 2185 } 2186 } 2187 2188 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 2189 auto *FN = Builder.GetInsertBlock()->getParent(); 2190 auto Arg = FN->arg_begin(); 2191 2192 bool StoredScalar = false; 2193 for (long i = 0; i < Kernel->n_array; i++) { 2194 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2195 continue; 2196 2197 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2198 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id)); 2199 isl_id_free(Id); 2200 2201 if (SAI->getNumberOfDimensions() > 0) { 2202 Arg++; 2203 continue; 2204 } 2205 2206 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 2207 Arg++; 2208 continue; 2209 } 2210 2211 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2212 Value *ArgPtr = &*Arg; 2213 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2214 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 2215 Value *Val = Builder.CreateLoad(SAI->getElementType(), Alloca); 2216 Builder.CreateStore(Val, TypedArgPtr); 2217 StoredScalar = true; 2218 2219 Arg++; 2220 } 2221 2222 if (StoredScalar) { 2223 /// In case more than one thread contains scalar stores, the generated 2224 /// code might be incorrect, if we only store at the end of the kernel. 2225 /// To support this case we need to store these scalars back at each 2226 /// memory store or at least before each kernel barrier. 2227 if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 2228 BuildSuccessful = 0; 2229 LLVM_DEBUG( 2230 dbgs() << getUniqueScopName(&S) 2231 << " has a store to a scalar value that" 2232 " would be undefined to run in parallel. Bailing out.\n";); 2233 } 2234 } 2235 } 2236 2237 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2238 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2239 2240 for (int i = 0; i < Kernel->n_var; ++i) { 2241 struct ppcg_kernel_var &Var = Kernel->var[i]; 2242 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2243 Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2244 2245 Type *ArrayTy = EleTy; 2246 SmallVector<const SCEV *, 4> Sizes; 2247 2248 Sizes.push_back(nullptr); 2249 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2250 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2251 long Bound = isl_val_get_num_si(Val); 2252 isl_val_free(Val); 2253 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2254 } 2255 2256 for (int j = Var.array->n_index - 1; j >= 0; --j) { 2257 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2258 long Bound = isl_val_get_num_si(Val); 2259 isl_val_free(Val); 2260 ArrayTy = ArrayType::get(ArrayTy, Bound); 2261 } 2262 2263 const ScopArrayInfo *SAI; 2264 Value *Allocation; 2265 if (Var.type == ppcg_access_shared) { 2266 auto GlobalVar = new GlobalVariable( 2267 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2268 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2269 GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8)); 2270 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2271 2272 Allocation = GlobalVar; 2273 } else if (Var.type == ppcg_access_private) { 2274 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2275 } else { 2276 llvm_unreachable("unknown variable type"); 2277 } 2278 SAI = 2279 S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2280 Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr); 2281 IDToValue[Id] = Allocation; 2282 LocalArrays.push_back(Allocation); 2283 KernelIds.push_back(Id); 2284 IDToSAI[Id] = SAI; 2285 } 2286 } 2287 2288 void GPUNodeBuilder::createKernelFunction( 2289 ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2290 SetVector<Function *> &SubtreeFunctions) { 2291 std::string Identifier = getKernelFuncName(Kernel->id); 2292 GPUModule.reset(new Module(Identifier, Builder.getContext())); 2293 2294 switch (Arch) { 2295 case GPUArch::NVPTX64: 2296 if (Runtime == GPURuntime::CUDA) 2297 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2298 else if (Runtime == GPURuntime::OpenCL) 2299 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 2300 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 2301 break; 2302 case GPUArch::SPIR32: 2303 GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 2304 GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 2305 break; 2306 case GPUArch::SPIR64: 2307 GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 2308 GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 2309 break; 2310 } 2311 2312 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 2313 2314 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 2315 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 2316 2317 DT.addNewBlock(EntryBlock, PrevBlock); 2318 2319 Builder.SetInsertPoint(EntryBlock); 2320 Builder.CreateRetVoid(); 2321 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2322 2323 ScopDetection::markFunctionAsInvalid(FN); 2324 2325 prepareKernelArguments(Kernel, FN); 2326 createKernelVariables(Kernel, FN); 2327 2328 switch (Arch) { 2329 case GPUArch::NVPTX64: 2330 insertKernelIntrinsics(Kernel); 2331 break; 2332 case GPUArch::SPIR32: 2333 insertKernelCallsSPIR(Kernel, false); 2334 break; 2335 case GPUArch::SPIR64: 2336 insertKernelCallsSPIR(Kernel, true); 2337 break; 2338 } 2339 } 2340 2341 std::string GPUNodeBuilder::createKernelASM() { 2342 llvm::Triple GPUTriple; 2343 2344 switch (Arch) { 2345 case GPUArch::NVPTX64: 2346 switch (Runtime) { 2347 case GPURuntime::CUDA: 2348 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 2349 break; 2350 case GPURuntime::OpenCL: 2351 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 2352 break; 2353 } 2354 break; 2355 case GPUArch::SPIR64: 2356 case GPUArch::SPIR32: 2357 std::string SPIRAssembly; 2358 raw_string_ostream IROstream(SPIRAssembly); 2359 IROstream << *GPUModule; 2360 IROstream.flush(); 2361 return SPIRAssembly; 2362 } 2363 2364 std::string ErrMsg; 2365 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 2366 2367 if (!GPUTarget) { 2368 errs() << ErrMsg << "\n"; 2369 return ""; 2370 } 2371 2372 TargetOptions Options; 2373 Options.UnsafeFPMath = FastMath; 2374 2375 std::string subtarget; 2376 2377 switch (Arch) { 2378 case GPUArch::NVPTX64: 2379 subtarget = CudaVersion; 2380 break; 2381 case GPUArch::SPIR32: 2382 case GPUArch::SPIR64: 2383 llvm_unreachable("No subtarget for SPIR architecture"); 2384 } 2385 2386 std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 2387 GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 2388 2389 SmallString<0> ASMString; 2390 raw_svector_ostream ASMStream(ASMString); 2391 llvm::legacy::PassManager PM; 2392 2393 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 2394 2395 if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile, 2396 true /* verify */)) { 2397 errs() << "The target does not support generation of this file type!\n"; 2398 return ""; 2399 } 2400 2401 PM.run(*GPUModule); 2402 2403 return ASMStream.str().str(); 2404 } 2405 2406 bool GPUNodeBuilder::requiresCUDALibDevice() { 2407 bool RequiresLibDevice = false; 2408 for (Function &F : GPUModule->functions()) { 2409 if (!F.isDeclaration()) 2410 continue; 2411 2412 const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName()); 2413 if (CUDALibDeviceFunc.length() != 0) { 2414 // We need to handle the case where a module looks like this: 2415 // @expf(..) 2416 // @llvm.exp.f64(..) 2417 // Both of these functions would be renamed to `__nv_expf`. 2418 // 2419 // So, we must first check for the existence of the libdevice function. 2420 // If this exists, we replace our current function with it. 2421 // 2422 // If it does not exist, we rename the current function to the 2423 // libdevice functiono name. 2424 if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc)) 2425 F.replaceAllUsesWith(Replacement); 2426 else 2427 F.setName(CUDALibDeviceFunc); 2428 RequiresLibDevice = true; 2429 } 2430 } 2431 2432 return RequiresLibDevice; 2433 } 2434 2435 void GPUNodeBuilder::addCUDALibDevice() { 2436 if (Arch != GPUArch::NVPTX64) 2437 return; 2438 2439 if (requiresCUDALibDevice()) { 2440 SMDiagnostic Error; 2441 2442 errs() << CUDALibDevice << "\n"; 2443 auto LibDeviceModule = 2444 parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 2445 2446 if (!LibDeviceModule) { 2447 BuildSuccessful = false; 2448 report_fatal_error("Could not find or load libdevice. Skipping GPU " 2449 "kernel generation. Please set -polly-acc-libdevice " 2450 "accordingly.\n"); 2451 return; 2452 } 2453 2454 Linker L(*GPUModule); 2455 2456 // Set an nvptx64 target triple to avoid linker warnings. The original 2457 // triple of the libdevice files are nvptx-unknown-unknown. 2458 LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2459 L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 2460 } 2461 } 2462 2463 std::string GPUNodeBuilder::finalizeKernelFunction() { 2464 2465 if (verifyModule(*GPUModule)) { 2466 LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n"; 2467 GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2468 LLVM_DEBUG(dbgs() << "verifyModule Error:\n"; 2469 verifyModule(*GPUModule, &dbgs());); 2470 2471 if (FailOnVerifyModuleFailure) 2472 llvm_unreachable("VerifyModule failed."); 2473 2474 BuildSuccessful = false; 2475 return ""; 2476 } 2477 2478 addCUDALibDevice(); 2479 2480 if (DumpKernelIR) 2481 outs() << *GPUModule << "\n"; 2482 2483 if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 2484 // Optimize module. 2485 llvm::legacy::PassManager OptPasses; 2486 PassManagerBuilder PassBuilder; 2487 PassBuilder.OptLevel = 3; 2488 PassBuilder.SizeLevel = 0; 2489 PassBuilder.populateModulePassManager(OptPasses); 2490 OptPasses.run(*GPUModule); 2491 } 2492 2493 std::string Assembly = createKernelASM(); 2494 2495 if (DumpKernelASM) 2496 outs() << Assembly << "\n"; 2497 2498 GPUModule.release(); 2499 KernelIDs.clear(); 2500 2501 return Assembly; 2502 } 2503 /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2504 /// @param PwAffs The list of piecewise affine functions to create an 2505 /// `isl_pw_aff_list` from. We expect an rvalue ref because 2506 /// all the isl_pw_aff are used up by this function. 2507 /// 2508 /// @returns The `isl_pw_aff_list`. 2509 __isl_give isl_pw_aff_list * 2510 createPwAffList(isl_ctx *Context, 2511 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2512 isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2513 2514 for (unsigned i = 0; i < PwAffs.size(); i++) { 2515 List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2516 } 2517 return List; 2518 } 2519 2520 /// Align all the `PwAffs` such that they have the same parameter dimensions. 2521 /// 2522 /// We loop over all `pw_aff` and align all of their spaces together to 2523 /// create a common space for all the `pw_aff`. This common space is the 2524 /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2525 /// with the given `SeedSpace`. 2526 /// @param PwAffs The list of piecewise affine functions we want to align. 2527 /// This is an rvalue reference because the entire vector is 2528 /// used up by the end of the operation. 2529 /// @param SeedSpace The space to start the alignment process with. 2530 /// @returns A std::pair, whose first element is the aligned space, 2531 /// whose second element is the vector of aligned piecewise 2532 /// affines. 2533 static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2534 alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2535 __isl_take isl_space *SeedSpace) { 2536 assert(SeedSpace && "Invalid seed space given."); 2537 2538 isl_space *AlignSpace = SeedSpace; 2539 for (isl_pw_aff *PwAff : PwAffs) { 2540 isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2541 AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2542 } 2543 std::vector<isl_pw_aff *> AdjustedPwAffs; 2544 2545 for (unsigned i = 0; i < PwAffs.size(); i++) { 2546 isl_pw_aff *Adjusted = PwAffs[i]; 2547 assert(Adjusted && "Invalid pw_aff given."); 2548 Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2549 AdjustedPwAffs.push_back(Adjusted); 2550 } 2551 return std::make_pair(AlignSpace, AdjustedPwAffs); 2552 } 2553 2554 namespace { 2555 class PPCGCodeGeneration final : public ScopPass { 2556 public: 2557 static char ID; 2558 2559 GPURuntime Runtime = GPURuntime::CUDA; 2560 2561 GPUArch Architecture = GPUArch::NVPTX64; 2562 2563 /// The scop that is currently processed. 2564 Scop *S; 2565 2566 LoopInfo *LI; 2567 DominatorTree *DT; 2568 ScalarEvolution *SE; 2569 const DataLayout *DL; 2570 RegionInfo *RI; 2571 2572 PPCGCodeGeneration() : ScopPass(ID) { 2573 // Apply defaults. 2574 Runtime = GPURuntimeChoice; 2575 Architecture = GPUArchChoice; 2576 } 2577 2578 /// Construct compilation options for PPCG. 2579 /// 2580 /// @returns The compilation options. 2581 ppcg_options *createPPCGOptions() { 2582 auto DebugOptions = 2583 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2584 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2585 2586 DebugOptions->dump_schedule_constraints = false; 2587 DebugOptions->dump_schedule = false; 2588 DebugOptions->dump_final_schedule = false; 2589 DebugOptions->dump_sizes = false; 2590 DebugOptions->verbose = false; 2591 2592 Options->debug = DebugOptions; 2593 2594 Options->group_chains = false; 2595 Options->reschedule = true; 2596 Options->scale_tile_loops = false; 2597 Options->wrap = false; 2598 2599 Options->non_negative_parameters = false; 2600 Options->ctx = nullptr; 2601 Options->sizes = nullptr; 2602 2603 Options->tile = true; 2604 Options->tile_size = 32; 2605 2606 Options->isolate_full_tiles = false; 2607 2608 Options->use_private_memory = PrivateMemory; 2609 Options->use_shared_memory = SharedMemory; 2610 Options->max_shared_memory = 48 * 1024; 2611 2612 Options->target = PPCG_TARGET_CUDA; 2613 Options->openmp = false; 2614 Options->linearize_device_arrays = true; 2615 Options->allow_gnu_extensions = false; 2616 2617 Options->unroll_copy_shared = false; 2618 Options->unroll_gpu_tile = false; 2619 Options->live_range_reordering = true; 2620 2621 Options->live_range_reordering = true; 2622 Options->hybrid = false; 2623 Options->opencl_compiler_options = nullptr; 2624 Options->opencl_use_gpu = false; 2625 Options->opencl_n_include_file = 0; 2626 Options->opencl_include_files = nullptr; 2627 Options->opencl_print_kernel_types = false; 2628 Options->opencl_embed_kernel_code = false; 2629 2630 Options->save_schedule_file = nullptr; 2631 Options->load_schedule_file = nullptr; 2632 2633 return Options; 2634 } 2635 2636 /// Get a tagged access relation containing all accesses of type @p AccessTy. 2637 /// 2638 /// Instead of a normal access of the form: 2639 /// 2640 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2641 /// 2642 /// a tagged access has the form 2643 /// 2644 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2645 /// 2646 /// where 'id' is an additional space that references the memory access that 2647 /// triggered the access. 2648 /// 2649 /// @param AccessTy The type of the memory accesses to collect. 2650 /// 2651 /// @return The relation describing all tagged memory accesses. 2652 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2653 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release()); 2654 2655 for (auto &Stmt : *S) 2656 for (auto &Acc : Stmt) 2657 if (Acc->getType() == AccessTy) { 2658 isl_map *Relation = Acc->getAccessRelation().release(); 2659 Relation = 2660 isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2661 2662 isl_space *Space = isl_map_get_space(Relation); 2663 Space = isl_space_range(Space); 2664 Space = isl_space_from_range(Space); 2665 Space = 2666 isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2667 isl_map *Universe = isl_map_universe(Space); 2668 Relation = isl_map_domain_product(Relation, Universe); 2669 Accesses = isl_union_map_add_map(Accesses, Relation); 2670 } 2671 2672 return Accesses; 2673 } 2674 2675 /// Get the set of all read accesses, tagged with the access id. 2676 /// 2677 /// @see getTaggedAccesses 2678 isl_union_map *getTaggedReads() { 2679 return getTaggedAccesses(MemoryAccess::READ); 2680 } 2681 2682 /// Get the set of all may (and must) accesses, tagged with the access id. 2683 /// 2684 /// @see getTaggedAccesses 2685 isl_union_map *getTaggedMayWrites() { 2686 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2687 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2688 } 2689 2690 /// Get the set of all must accesses, tagged with the access id. 2691 /// 2692 /// @see getTaggedAccesses 2693 isl_union_map *getTaggedMustWrites() { 2694 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2695 } 2696 2697 /// Collect parameter and array names as isl_ids. 2698 /// 2699 /// To reason about the different parameters and arrays used, ppcg requires 2700 /// a list of all isl_ids in use. As PPCG traditionally performs 2701 /// source-to-source compilation each of these isl_ids is mapped to the 2702 /// expression that represents it. As we do not have a corresponding 2703 /// expression in Polly, we just map each id to a 'zero' expression to match 2704 /// the data format that ppcg expects. 2705 /// 2706 /// @returns Retun a map from collected ids to 'zero' ast expressions. 2707 __isl_give isl_id_to_ast_expr *getNames() { 2708 auto *Names = isl_id_to_ast_expr_alloc( 2709 S->getIslCtx().get(), 2710 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2711 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get())); 2712 2713 for (const SCEV *P : S->parameters()) { 2714 isl_id *Id = S->getIdForParam(P).release(); 2715 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2716 } 2717 2718 for (auto &Array : S->arrays()) { 2719 auto Id = Array->getBasePtrId().release(); 2720 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2721 } 2722 2723 isl_ast_expr_free(Zero); 2724 2725 return Names; 2726 } 2727 2728 /// Create a new PPCG scop from the current scop. 2729 /// 2730 /// The PPCG scop is initialized with data from the current polly::Scop. From 2731 /// this initial data, the data-dependences in the PPCG scop are initialized. 2732 /// We do not use Polly's dependence analysis for now, to ensure we match 2733 /// the PPCG default behaviour more closely. 2734 /// 2735 /// @returns A new ppcg scop. 2736 ppcg_scop *createPPCGScop() { 2737 MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2738 2739 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2740 2741 PPCGScop->options = createPPCGOptions(); 2742 // enable live range reordering 2743 PPCGScop->options->live_range_reordering = 1; 2744 2745 PPCGScop->start = 0; 2746 PPCGScop->end = 0; 2747 2748 PPCGScop->context = S->getContext().release(); 2749 PPCGScop->domain = S->getDomains().release(); 2750 // TODO: investigate this further. PPCG calls collect_call_domains. 2751 PPCGScop->call = isl_union_set_from_set(S->getContext().release()); 2752 PPCGScop->tagged_reads = getTaggedReads(); 2753 PPCGScop->reads = S->getReads().release(); 2754 PPCGScop->live_in = nullptr; 2755 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2756 PPCGScop->may_writes = S->getWrites().release(); 2757 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2758 PPCGScop->must_writes = S->getMustWrites().release(); 2759 PPCGScop->live_out = nullptr; 2760 PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release(); 2761 PPCGScop->must_kills = KillsInfo.MustKills.release(); 2762 2763 PPCGScop->tagger = nullptr; 2764 PPCGScop->independence = 2765 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2766 PPCGScop->dep_flow = nullptr; 2767 PPCGScop->tagged_dep_flow = nullptr; 2768 PPCGScop->dep_false = nullptr; 2769 PPCGScop->dep_forced = nullptr; 2770 PPCGScop->dep_order = nullptr; 2771 PPCGScop->tagged_dep_order = nullptr; 2772 2773 PPCGScop->schedule = S->getScheduleTree().release(); 2774 // If we have something non-trivial to kill, add it to the schedule 2775 if (KillsInfo.KillsSchedule.get()) 2776 PPCGScop->schedule = isl_schedule_sequence( 2777 PPCGScop->schedule, KillsInfo.KillsSchedule.release()); 2778 2779 PPCGScop->names = getNames(); 2780 PPCGScop->pet = nullptr; 2781 2782 compute_tagger(PPCGScop); 2783 compute_dependences(PPCGScop); 2784 eliminate_dead_code(PPCGScop); 2785 2786 return PPCGScop; 2787 } 2788 2789 /// Collect the array accesses in a statement. 2790 /// 2791 /// @param Stmt The statement for which to collect the accesses. 2792 /// 2793 /// @returns A list of array accesses. 2794 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 2795 gpu_stmt_access *Accesses = nullptr; 2796 2797 for (MemoryAccess *Acc : Stmt) { 2798 auto Access = 2799 isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access); 2800 Access->read = Acc->isRead(); 2801 Access->write = Acc->isWrite(); 2802 Access->access = Acc->getAccessRelation().release(); 2803 isl_space *Space = isl_map_get_space(Access->access); 2804 Space = isl_space_range(Space); 2805 Space = isl_space_from_range(Space); 2806 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2807 isl_map *Universe = isl_map_universe(Space); 2808 Access->tagged_access = 2809 isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2810 Access->exact_write = !Acc->isMayWrite(); 2811 Access->ref_id = Acc->getId().release(); 2812 Access->next = Accesses; 2813 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2814 // TODO: Also mark one-element accesses to arrays as fixed-element. 2815 Access->fixed_element = 2816 Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false; 2817 Accesses = Access; 2818 } 2819 2820 return Accesses; 2821 } 2822 2823 /// Collect the list of GPU statements. 2824 /// 2825 /// Each statement has an id, a pointer to the underlying data structure, 2826 /// as well as a list with all memory accesses. 2827 /// 2828 /// TODO: Initialize the list of memory accesses. 2829 /// 2830 /// @returns A linked-list of statements. 2831 gpu_stmt *getStatements() { 2832 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt, 2833 std::distance(S->begin(), S->end())); 2834 2835 int i = 0; 2836 for (auto &Stmt : *S) { 2837 gpu_stmt *GPUStmt = &Stmts[i]; 2838 2839 GPUStmt->id = Stmt.getDomainId().release(); 2840 2841 // We use the pet stmt pointer to keep track of the Polly statements. 2842 GPUStmt->stmt = (pet_stmt *)&Stmt; 2843 GPUStmt->accesses = getStmtAccesses(Stmt); 2844 i++; 2845 } 2846 2847 return Stmts; 2848 } 2849 2850 /// Derive the extent of an array. 2851 /// 2852 /// The extent of an array is the set of elements that are within the 2853 /// accessed array. For the inner dimensions, the extent constraints are 2854 /// 0 and the size of the corresponding array dimension. For the first 2855 /// (outermost) dimension, the extent constraints are the minimal and maximal 2856 /// subscript value for the first dimension. 2857 /// 2858 /// @param Array The array to derive the extent for. 2859 /// 2860 /// @returns An isl_set describing the extent of the array. 2861 isl::set getExtent(ScopArrayInfo *Array) { 2862 unsigned NumDims = Array->getNumberOfDimensions(); 2863 2864 if (Array->getNumberOfDimensions() == 0) 2865 return isl::set::universe(Array->getSpace()); 2866 2867 isl::union_map Accesses = S->getAccesses(Array); 2868 isl::union_set AccessUSet = Accesses.range(); 2869 AccessUSet = AccessUSet.coalesce(); 2870 AccessUSet = AccessUSet.detect_equalities(); 2871 AccessUSet = AccessUSet.coalesce(); 2872 2873 if (AccessUSet.is_empty()) 2874 return isl::set::empty(Array->getSpace()); 2875 2876 isl::set AccessSet = AccessUSet.extract_set(Array->getSpace()); 2877 2878 isl::local_space LS = isl::local_space(Array->getSpace()); 2879 2880 isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0); 2881 isl::pw_aff OuterMin = AccessSet.dim_min(0); 2882 isl::pw_aff OuterMax = AccessSet.dim_max(0); 2883 OuterMin = OuterMin.add_dims(isl::dim::in, 2884 unsignedFromIslSize(Val.dim(isl::dim::in))); 2885 OuterMax = OuterMax.add_dims(isl::dim::in, 2886 unsignedFromIslSize(Val.dim(isl::dim::in))); 2887 OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2888 OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId()); 2889 2890 isl::set Extent = isl::set::universe(Array->getSpace()); 2891 2892 Extent = Extent.intersect(OuterMin.le_set(Val)); 2893 Extent = Extent.intersect(OuterMax.ge_set(Val)); 2894 2895 for (unsigned i = 1; i < NumDims; ++i) 2896 Extent = Extent.lower_bound_si(isl::dim::set, i, 0); 2897 2898 for (unsigned i = 0; i < NumDims; ++i) { 2899 isl::pw_aff PwAff = Array->getDimensionSizePw(i); 2900 2901 // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2902 // Fortran array will we have a legitimate dimension. 2903 if (PwAff.is_null()) { 2904 assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2905 continue; 2906 } 2907 2908 isl::pw_aff Val = isl::aff::var_on_domain( 2909 isl::local_space(Array->getSpace()), isl::dim::set, i); 2910 PwAff = PwAff.add_dims(isl::dim::in, 2911 unsignedFromIslSize(Val.dim(isl::dim::in))); 2912 PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in)); 2913 isl::set Set = PwAff.gt_set(Val); 2914 Extent = Set.intersect(Extent); 2915 } 2916 2917 return Extent; 2918 } 2919 2920 /// Derive the bounds of an array. 2921 /// 2922 /// For the first dimension we derive the bound of the array from the extent 2923 /// of this dimension. For inner dimensions we obtain their size directly from 2924 /// ScopArrayInfo. 2925 /// 2926 /// @param PPCGArray The array to compute bounds for. 2927 /// @param Array The polly array from which to take the information. 2928 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2929 std::vector<isl_pw_aff *> Bounds; 2930 2931 if (PPCGArray.n_index > 0) { 2932 if (isl_set_is_empty(PPCGArray.extent)) { 2933 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2934 isl_local_space *LS = isl_local_space_from_space( 2935 isl_space_params(isl_set_get_space(Dom))); 2936 isl_set_free(Dom); 2937 isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2938 Bounds.push_back(Zero); 2939 } else { 2940 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2941 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 2942 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 2943 isl_set_free(Dom); 2944 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 2945 isl_local_space *LS = 2946 isl_local_space_from_space(isl_set_get_space(Dom)); 2947 isl_aff *One = isl_aff_zero_on_domain(LS); 2948 One = isl_aff_add_constant_si(One, 1); 2949 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 2950 Bound = isl_pw_aff_gist(Bound, S->getContext().release()); 2951 Bounds.push_back(Bound); 2952 } 2953 } 2954 2955 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2956 isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 2957 auto LS = isl_pw_aff_get_domain_space(Bound); 2958 auto Aff = isl_multi_aff_zero(LS); 2959 2960 // We need types to work out, which is why we perform this weird dance 2961 // with `Aff` and `Bound`. Consider this example: 2962 2963 // LS: [p] -> { [] } 2964 // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }. 2965 // This `~` is used to denote a "null space" (which is different from 2966 // a *zero dimensional* space), which is something that ISL does not 2967 // show you when pretty printing. 2968 2969 // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional* 2970 // space, not a "null space" which does not exist at all. 2971 2972 // When we pullback (precompose) `Bound` with `Zero`, we get: 2973 // Bound . Zero = 2974 // ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) = 2975 // [p] -> { ~ -> [(10p)] } = 2976 // [p] -> [(10p)] (as ISL pretty prints it) 2977 // Bound Pullback: [p] -> { [(10p)] } 2978 2979 // We want this kind of an expression for Bound, without a 2980 // zero dimensional input, but with a "null space" input for the types 2981 // to work out later on, as far as I (Siddharth Bhat) understand. 2982 // I was unable to find a reference to this in the ISL manual. 2983 // References: Tobias Grosser. 2984 2985 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2986 Bounds.push_back(Bound); 2987 } 2988 2989 /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2990 /// to have the same parameter dimensions. So, we need to align them to an 2991 /// appropriate space. 2992 /// Scop::Context is _not_ an appropriate space, because when we have 2993 /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 2994 /// contain all parameter dimensions. 2995 /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 2996 isl_space *SeedAlignSpace = S->getParamSpace().release(); 2997 SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 2998 2999 isl_space *AlignSpace = nullptr; 3000 std::vector<isl_pw_aff *> AlignedBounds; 3001 std::tie(AlignSpace, AlignedBounds) = 3002 alignPwAffs(std::move(Bounds), SeedAlignSpace); 3003 3004 assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 3005 3006 isl_pw_aff_list *BoundsList = 3007 createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds)); 3008 3009 isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 3010 BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 3011 3012 assert(BoundsSpace && "Unable to access space of array."); 3013 assert(BoundsList && "Unable to access list of bounds."); 3014 3015 PPCGArray.bound = 3016 isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 3017 assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 3018 } 3019 3020 /// Create the arrays for @p PPCGProg. 3021 /// 3022 /// @param PPCGProg The program to compute the arrays for. 3023 void createArrays(gpu_prog *PPCGProg, 3024 const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 3025 int i = 0; 3026 for (auto &Array : ValidSAIs) { 3027 std::string TypeName; 3028 raw_string_ostream OS(TypeName); 3029 3030 OS << *Array->getElementType(); 3031 TypeName = OS.str(); 3032 3033 gpu_array_info &PPCGArray = PPCGProg->array[i]; 3034 3035 PPCGArray.space = Array->getSpace().release(); 3036 PPCGArray.type = strdup(TypeName.c_str()); 3037 PPCGArray.size = DL->getTypeAllocSize(Array->getElementType()); 3038 PPCGArray.name = strdup(Array->getName().c_str()); 3039 PPCGArray.extent = nullptr; 3040 PPCGArray.n_index = Array->getNumberOfDimensions(); 3041 PPCGArray.extent = getExtent(Array).release(); 3042 PPCGArray.n_ref = 0; 3043 PPCGArray.refs = nullptr; 3044 PPCGArray.accessed = true; 3045 PPCGArray.read_only_scalar = 3046 Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 3047 PPCGArray.has_compound_element = false; 3048 PPCGArray.local = false; 3049 PPCGArray.declare_local = false; 3050 PPCGArray.global = false; 3051 PPCGArray.linearize = false; 3052 PPCGArray.dep_order = nullptr; 3053 PPCGArray.user = Array; 3054 3055 PPCGArray.bound = nullptr; 3056 setArrayBounds(PPCGArray, Array); 3057 i++; 3058 3059 collect_references(PPCGProg, &PPCGArray); 3060 PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray); 3061 } 3062 } 3063 3064 /// Create an identity map between the arrays in the scop. 3065 /// 3066 /// @returns An identity map between the arrays in the scop. 3067 isl_union_map *getArrayIdentity() { 3068 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release()); 3069 3070 for (auto &Array : S->arrays()) { 3071 isl_space *Space = Array->getSpace().release(); 3072 Space = isl_space_map_from_set(Space); 3073 isl_map *Identity = isl_map_identity(Space); 3074 Maps = isl_union_map_add_map(Maps, Identity); 3075 } 3076 3077 return Maps; 3078 } 3079 3080 /// Create a default-initialized PPCG GPU program. 3081 /// 3082 /// @returns A new gpu program description. 3083 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 3084 3085 if (!PPCGScop) 3086 return nullptr; 3087 3088 auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog); 3089 3090 PPCGProg->ctx = S->getIslCtx().get(); 3091 PPCGProg->scop = PPCGScop; 3092 PPCGProg->context = isl_set_copy(PPCGScop->context); 3093 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 3094 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 3095 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 3096 PPCGProg->tagged_must_kill = 3097 isl_union_map_copy(PPCGScop->tagged_must_kills); 3098 PPCGProg->to_inner = getArrayIdentity(); 3099 PPCGProg->to_outer = getArrayIdentity(); 3100 // TODO: verify that this assignment is correct. 3101 PPCGProg->any_to_outer = nullptr; 3102 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 3103 PPCGProg->stmts = getStatements(); 3104 3105 // Only consider arrays that have a non-empty extent. 3106 // Otherwise, this will cause us to consider the following kinds of 3107 // empty arrays: 3108 // 1. Invariant loads that are represented by SAI objects. 3109 // 2. Arrays with statically known zero size. 3110 auto ValidSAIsRange = 3111 make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 3112 return !getExtent(SAI).is_empty(); 3113 }); 3114 SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 3115 ValidSAIsRange.end()); 3116 3117 PPCGProg->n_array = 3118 ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 3119 PPCGProg->array = isl_calloc_array( 3120 S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array); 3121 3122 createArrays(PPCGProg, ValidSAIs); 3123 3124 PPCGProg->array_order = nullptr; 3125 collect_order_dependences(PPCGProg); 3126 3127 PPCGProg->may_persist = compute_may_persist(PPCGProg); 3128 return PPCGProg; 3129 } 3130 3131 struct PrintGPUUserData { 3132 struct cuda_info *CudaInfo; 3133 struct gpu_prog *PPCGProg; 3134 std::vector<ppcg_kernel *> Kernels; 3135 }; 3136 3137 /// Print a user statement node in the host code. 3138 /// 3139 /// We use ppcg's printing facilities to print the actual statement and 3140 /// additionally build up a list of all kernels that are encountered in the 3141 /// host ast. 3142 /// 3143 /// @param P The printer to print to 3144 /// @param Options The printing options to use 3145 /// @param Node The node to print 3146 /// @param User A user pointer to carry additional data. This pointer is 3147 /// expected to be of type PrintGPUUserData. 3148 /// 3149 /// @returns A printer to which the output has been printed. 3150 static __isl_give isl_printer * 3151 printHostUser(__isl_take isl_printer *P, 3152 __isl_take isl_ast_print_options *Options, 3153 __isl_take isl_ast_node *Node, void *User) { 3154 auto Data = (struct PrintGPUUserData *)User; 3155 auto Id = isl_ast_node_get_annotation(Node); 3156 3157 if (Id) { 3158 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 3159 3160 // If this is a user statement, format it ourselves as ppcg would 3161 // otherwise try to call pet functionality that is not available in 3162 // Polly. 3163 if (IsUser) { 3164 P = isl_printer_start_line(P); 3165 P = isl_printer_print_ast_node(P, Node); 3166 P = isl_printer_end_line(P); 3167 isl_id_free(Id); 3168 isl_ast_print_options_free(Options); 3169 return P; 3170 } 3171 3172 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 3173 isl_id_free(Id); 3174 Data->Kernels.push_back(Kernel); 3175 } 3176 3177 return print_host_user(P, Options, Node, User); 3178 } 3179 3180 /// Print C code corresponding to the control flow in @p Kernel. 3181 /// 3182 /// @param Kernel The kernel to print 3183 void printKernel(ppcg_kernel *Kernel) { 3184 auto *P = isl_printer_to_str(S->getIslCtx().get()); 3185 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 3186 auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get()); 3187 P = isl_ast_node_print(Kernel->tree, P, Options); 3188 char *String = isl_printer_get_str(P); 3189 outs() << String << "\n"; 3190 free(String); 3191 isl_printer_free(P); 3192 } 3193 3194 /// Print C code corresponding to the GPU code described by @p Tree. 3195 /// 3196 /// @param Tree An AST describing GPU code 3197 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 3198 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 3199 auto *P = isl_printer_to_str(S->getIslCtx().get()); 3200 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 3201 3202 PrintGPUUserData Data; 3203 Data.PPCGProg = PPCGProg; 3204 3205 auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get()); 3206 Options = 3207 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 3208 P = isl_ast_node_print(Tree, P, Options); 3209 char *String = isl_printer_get_str(P); 3210 outs() << "# host\n"; 3211 outs() << String << "\n"; 3212 free(String); 3213 isl_printer_free(P); 3214 3215 for (auto Kernel : Data.Kernels) { 3216 outs() << "# kernel" << Kernel->id << "\n"; 3217 printKernel(Kernel); 3218 } 3219 } 3220 3221 // Generate a GPU program using PPCG. 3222 // 3223 // GPU mapping consists of multiple steps: 3224 // 3225 // 1) Compute new schedule for the program. 3226 // 2) Map schedule to GPU (TODO) 3227 // 3) Generate code for new schedule (TODO) 3228 // 3229 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3230 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3231 // strategy directly from this pass. 3232 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3233 3234 auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen); 3235 3236 PPCGGen->ctx = S->getIslCtx().get(); 3237 PPCGGen->options = PPCGScop->options; 3238 PPCGGen->print = nullptr; 3239 PPCGGen->print_user = nullptr; 3240 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3241 PPCGGen->prog = PPCGProg; 3242 PPCGGen->tree = nullptr; 3243 PPCGGen->types.n = 0; 3244 PPCGGen->types.name = nullptr; 3245 PPCGGen->sizes = nullptr; 3246 PPCGGen->used_sizes = nullptr; 3247 PPCGGen->kernel_id = 0; 3248 3249 // Set scheduling strategy to same strategy PPCG is using. 3250 isl_options_set_schedule_serialize_sccs(PPCGGen->ctx, false); 3251 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3252 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 3253 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3254 3255 isl_schedule *Schedule = get_schedule(PPCGGen); 3256 3257 int has_permutable = has_any_permutable_node(Schedule); 3258 3259 Schedule = 3260 isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3261 3262 if (!has_permutable || has_permutable < 0) { 3263 Schedule = isl_schedule_free(Schedule); 3264 LLVM_DEBUG(dbgs() << getUniqueScopName(S) 3265 << " does not have permutable bands. Bailing out\n";); 3266 } else { 3267 const bool CreateTransferToFromDevice = !PollyManagedMemory; 3268 Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice); 3269 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 3270 } 3271 3272 if (DumpSchedule) { 3273 isl_printer *P = isl_printer_to_str(S->getIslCtx().get()); 3274 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3275 P = isl_printer_print_str(P, "Schedule\n"); 3276 P = isl_printer_print_str(P, "========\n"); 3277 if (Schedule) 3278 P = isl_printer_print_schedule(P, Schedule); 3279 else 3280 P = isl_printer_print_str(P, "No schedule found\n"); 3281 3282 outs() << isl_printer_get_str(P) << "\n"; 3283 isl_printer_free(P); 3284 } 3285 3286 if (DumpCode) { 3287 outs() << "Code\n"; 3288 outs() << "====\n"; 3289 if (PPCGGen->tree) 3290 printGPUTree(PPCGGen->tree, PPCGProg); 3291 else 3292 outs() << "No code generated\n"; 3293 } 3294 3295 isl_schedule_free(Schedule); 3296 3297 return PPCGGen; 3298 } 3299 3300 /// Free gpu_gen structure. 3301 /// 3302 /// @param PPCGGen The ppcg_gen object to free. 3303 void freePPCGGen(gpu_gen *PPCGGen) { 3304 isl_ast_node_free(PPCGGen->tree); 3305 isl_union_map_free(PPCGGen->sizes); 3306 isl_union_map_free(PPCGGen->used_sizes); 3307 free(PPCGGen); 3308 } 3309 3310 /// Free the options in the ppcg scop structure. 3311 /// 3312 /// ppcg is not freeing these options for us. To avoid leaks we do this 3313 /// ourselves. 3314 /// 3315 /// @param PPCGScop The scop referencing the options to free. 3316 void freeOptions(ppcg_scop *PPCGScop) { 3317 free(PPCGScop->options->debug); 3318 PPCGScop->options->debug = nullptr; 3319 free(PPCGScop->options); 3320 PPCGScop->options = nullptr; 3321 } 3322 3323 /// Approximate the number of points in the set. 3324 /// 3325 /// This function returns an ast expression that overapproximates the number 3326 /// of points in an isl set through the rectangular hull surrounding this set. 3327 /// 3328 /// @param Set The set to count. 3329 /// @param Build The isl ast build object to use for creating the ast 3330 /// expression. 3331 /// 3332 /// @returns An approximation of the number of points in the set. 3333 __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 3334 __isl_keep isl_ast_build *Build) { 3335 3336 isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 3337 auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 3338 3339 isl_space *Space = isl_set_get_space(Set); 3340 Space = isl_space_params(Space); 3341 auto *Univ = isl_set_universe(Space); 3342 isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 3343 3344 for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) { 3345 isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 3346 isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 3347 isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 3348 DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 3349 auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 3350 Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 3351 } 3352 3353 isl_set_free(Set); 3354 isl_pw_aff_free(OneAff); 3355 3356 return Expr; 3357 } 3358 3359 /// Approximate a number of dynamic instructions executed by a given 3360 /// statement. 3361 /// 3362 /// @param Stmt The statement for which to compute the number of dynamic 3363 /// instructions. 3364 /// @param Build The isl ast build object to use for creating the ast 3365 /// expression. 3366 /// @returns An approximation of the number of dynamic instructions executed 3367 /// by @p Stmt. 3368 __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 3369 __isl_keep isl_ast_build *Build) { 3370 auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 3371 3372 long InstCount = 0; 3373 3374 if (Stmt.isBlockStmt()) { 3375 auto *BB = Stmt.getBasicBlock(); 3376 InstCount = std::distance(BB->begin(), BB->end()); 3377 } else { 3378 auto *R = Stmt.getRegion(); 3379 3380 for (auto *BB : R->blocks()) { 3381 InstCount += std::distance(BB->begin(), BB->end()); 3382 } 3383 } 3384 3385 isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount); 3386 auto *InstExpr = isl_ast_expr_from_val(InstVal); 3387 return isl_ast_expr_mul(InstExpr, Iterations); 3388 } 3389 3390 /// Approximate dynamic instructions executed in scop. 3391 /// 3392 /// @param S The scop for which to approximate dynamic instructions. 3393 /// @param Build The isl ast build object to use for creating the ast 3394 /// expression. 3395 /// @returns An approximation of the number of dynamic instructions executed 3396 /// in @p S. 3397 __isl_give isl_ast_expr * 3398 getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 3399 isl_ast_expr *Instructions; 3400 3401 isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0); 3402 Instructions = isl_ast_expr_from_val(Zero); 3403 3404 for (ScopStmt &Stmt : S) { 3405 isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 3406 Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 3407 } 3408 return Instructions; 3409 } 3410 3411 /// Create a check that ensures sufficient compute in scop. 3412 /// 3413 /// @param S The scop for which to ensure sufficient compute. 3414 /// @param Build The isl ast build object to use for creating the ast 3415 /// expression. 3416 /// @returns An expression that evaluates to TRUE in case of sufficient 3417 /// compute and to FALSE, otherwise. 3418 __isl_give isl_ast_expr * 3419 createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 3420 auto Iterations = getNumberOfIterations(S, Build); 3421 auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute); 3422 auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 3423 return isl_ast_expr_ge(Iterations, MinComputeExpr); 3424 } 3425 3426 /// Check if the basic block contains a function we cannot codegen for GPU 3427 /// kernels. 3428 /// 3429 /// If this basic block does something with a `Function` other than calling 3430 /// a function that we support in a kernel, return true. 3431 bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 3432 bool AllowCUDALibDevice) { 3433 for (const Instruction &Inst : *BB) { 3434 const CallInst *Call = dyn_cast<CallInst>(&Inst); 3435 if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 3436 AllowCUDALibDevice)) 3437 continue; 3438 3439 for (Value *Op : Inst.operands()) 3440 // Look for functions among operands of Inst. 3441 if (isa<Function>(Op->stripPointerCasts())) { 3442 LLVM_DEBUG(dbgs() 3443 << Inst << " has illegal use of function in kernel.\n"); 3444 return true; 3445 } 3446 } 3447 return false; 3448 } 3449 3450 /// Return whether the Scop S uses functions in a way that we do not support. 3451 bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3452 for (auto &Stmt : S) { 3453 if (Stmt.isBlockStmt()) { 3454 if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 3455 AllowCUDALibDevice)) 3456 return true; 3457 } else { 3458 assert(Stmt.isRegionStmt() && 3459 "Stmt was neither block nor region statement"); 3460 for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 3461 if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3462 return true; 3463 } 3464 } 3465 return false; 3466 } 3467 3468 /// Generate code for a given GPU AST described by @p Root. 3469 /// 3470 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 3471 /// @param Prog The GPU Program to generate code for. 3472 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 3473 ScopAnnotator Annotator; 3474 Annotator.buildAliasScopes(*S); 3475 3476 Region *R = &S->getRegion(); 3477 3478 simplifyRegion(R, DT, LI, RI); 3479 3480 BasicBlock *EnteringBB = R->getEnteringBlock(); 3481 3482 PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(), 3483 IRInserter(Annotator)); 3484 Builder.SetInsertPoint(EnteringBB->getTerminator()); 3485 3486 // Only build the run-time condition and parameters _after_ having 3487 // introduced the conditional branch. This is important as the conditional 3488 // branch will guard the original scop from new induction variables that 3489 // the SCEVExpander may introduce while code generating the parameters and 3490 // which may introduce scalar dependences that prevent us from correctly 3491 // code generating this scop. 3492 BBPair StartExitBlocks; 3493 BranchInst *CondBr = nullptr; 3494 std::tie(StartExitBlocks, CondBr) = 3495 executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3496 BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 3497 3498 assert(CondBr && "CondBr not initialized by executeScopConditionally"); 3499 3500 GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 3501 StartBlock, Prog, Runtime, Architecture); 3502 3503 // TODO: Handle LICM 3504 auto SplitBlock = StartBlock->getSinglePredecessor(); 3505 Builder.SetInsertPoint(SplitBlock->getTerminator()); 3506 3507 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get()); 3508 isl::ast_expr Condition = 3509 IslAst::buildRunCondition(*S, isl::manage_copy(Build)); 3510 isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 3511 Condition = 3512 isl::manage(isl_ast_expr_and(Condition.release(), SufficientCompute)); 3513 isl_ast_build_free(Build); 3514 3515 // preload invariant loads. Note: This should happen before the RTC 3516 // because the RTC may depend on values that are invariant load hoisted. 3517 if (!NodeBuilder.preloadInvariantLoads()) { 3518 // Patch the introduced branch condition to ensure that we always execute 3519 // the original SCoP. 3520 auto *FalseI1 = Builder.getFalse(); 3521 auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator(); 3522 SplitBBTerm->setOperand(0, FalseI1); 3523 3524 LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " + 3525 S->getFunction().getName() + 3526 " | Scop Region: " + S->getNameStr()); 3527 // adjust the dominator tree accordingly. 3528 auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 3529 assert(ExitingBlock); 3530 auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 3531 assert(MergeBlock); 3532 polly::markBlockUnreachable(*StartBlock, Builder); 3533 polly::markBlockUnreachable(*ExitingBlock, Builder); 3534 auto *ExitingBB = S->getExitingBlock(); 3535 assert(ExitingBB); 3536 3537 DT->changeImmediateDominator(MergeBlock, ExitingBB); 3538 DT->eraseNode(ExitingBlock); 3539 isl_ast_node_free(Root); 3540 } else { 3541 3542 if (polly::PerfMonitoring) { 3543 PerfMonitor P(*S, EnteringBB->getParent()->getParent()); 3544 P.initialize(); 3545 P.insertRegionStart(SplitBlock->getTerminator()); 3546 3547 // TODO: actually think if this is the correct exiting block to place 3548 // the `end` performance marker. Invariant load hoisting changes 3549 // the CFG in a way that I do not precisely understand, so I 3550 // (Siddharth<[email protected]>) should come back to this and 3551 // think about which exiting block to use. 3552 auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 3553 assert(ExitingBlock); 3554 BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor(); 3555 P.insertRegionEnd(MergeBlock->getTerminator()); 3556 } 3557 3558 NodeBuilder.addParameters(S->getContext().release()); 3559 Value *RTC = NodeBuilder.createRTC(Condition.release()); 3560 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3561 3562 Builder.SetInsertPoint(&*StartBlock->begin()); 3563 3564 NodeBuilder.create(Root); 3565 } 3566 3567 /// In case a sequential kernel has more surrounding loops as any parallel 3568 /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3569 /// point in running it on a GPU. 3570 if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 3571 CondBr->setOperand(0, Builder.getFalse()); 3572 3573 if (!NodeBuilder.BuildSuccessful) 3574 CondBr->setOperand(0, Builder.getFalse()); 3575 } 3576 3577 bool runOnScop(Scop &CurrentScop) override { 3578 S = &CurrentScop; 3579 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3580 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3581 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 3582 DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 3583 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3584 3585 LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S) 3586 << " | loop depth: " << S->getMaxLoopDepth() << "\n"); 3587 3588 // We currently do not support functions other than intrinsics inside 3589 // kernels, as code generation will need to offload function calls to the 3590 // kernel. This may lead to a kernel trying to call a function on the host. 3591 // This also allows us to prevent codegen from trying to take the 3592 // address of an intrinsic function to send to the kernel. 3593 if (containsInvalidKernelFunction(CurrentScop, 3594 Architecture == GPUArch::NVPTX64)) { 3595 LLVM_DEBUG( 3596 dbgs() << getUniqueScopName(S) 3597 << " contains function which cannot be materialised in a GPU " 3598 "kernel. Bailing out.\n";); 3599 return false; 3600 } 3601 3602 auto PPCGScop = createPPCGScop(); 3603 auto PPCGProg = createPPCGProg(PPCGScop); 3604 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 3605 3606 if (PPCGGen->tree) { 3607 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 3608 CurrentScop.markAsToBeSkipped(); 3609 } else { 3610 LLVM_DEBUG(dbgs() << getUniqueScopName(S) 3611 << " has empty PPCGGen->tree. Bailing out.\n"); 3612 } 3613 3614 freeOptions(PPCGScop); 3615 freePPCGGen(PPCGGen); 3616 gpu_prog_free(PPCGProg); 3617 ppcg_scop_free(PPCGScop); 3618 3619 return true; 3620 } 3621 3622 void printScop(raw_ostream &, Scop &) const override {} 3623 3624 void getAnalysisUsage(AnalysisUsage &AU) const override { 3625 ScopPass::getAnalysisUsage(AU); 3626 3627 AU.addRequired<DominatorTreeWrapperPass>(); 3628 AU.addRequired<RegionInfoPass>(); 3629 AU.addRequired<ScalarEvolutionWrapperPass>(); 3630 AU.addRequired<ScopDetectionWrapperPass>(); 3631 AU.addRequired<ScopInfoRegionPass>(); 3632 AU.addRequired<LoopInfoWrapperPass>(); 3633 3634 // FIXME: We do not yet add regions for the newly generated code to the 3635 // region tree. 3636 } 3637 }; 3638 } // namespace 3639 3640 char PPCGCodeGeneration::ID = 1; 3641 3642 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 3643 PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 3644 generator->Runtime = Runtime; 3645 generator->Architecture = Arch; 3646 return generator; 3647 } 3648 3649 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 3650 "Polly - Apply PPCG translation to SCOP", false, false) 3651 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 3652 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 3653 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 3654 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 3655 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 3656 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 3657 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 3658 "Polly - Apply PPCG translation to SCOP", false, false) 3659