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