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(isl::manage(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()); 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 = 1074 isl::ast_build::from_context(isl::manage(S.getContext())); 1075 Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 1076 1077 if (!gpu_array_is_scalar(Array)) { 1078 isl::multi_pw_aff ArrayBound = 1079 isl::manage(isl_multi_pw_aff_copy(Array->bound)); 1080 1081 isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0); 1082 isl::ast_expr Res = Build.expr_from(OffsetDimZero); 1083 1084 for (unsigned int i = 1; i < Array->n_index; i++) { 1085 isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i); 1086 isl::ast_expr Expr = Build.expr_from(Bound_I); 1087 Res = Res.mul(Expr); 1088 } 1089 1090 Value *NumElements = ExprBuilder.create(Res.release()); 1091 if (NumElements->getType() != ArraySize->getType()) 1092 NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 1093 ArraySize = Builder.CreateMul(ArraySize, NumElements); 1094 } 1095 return ArraySize; 1096 } 1097 1098 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1099 if (gpu_array_is_scalar(Array)) 1100 return nullptr; 1101 1102 isl::ast_build Build = 1103 isl::ast_build::from_context(isl::manage(S.getContext())); 1104 1105 isl::set Min = isl::manage(isl_set_copy(Array->extent)).lexmin(); 1106 1107 isl::set ZeroSet = isl::set::universe(Min.get_space()); 1108 1109 for (long i = 0; i < Min.dim(isl::dim::set); i++) 1110 ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0); 1111 1112 if (Min.is_subset(ZeroSet)) { 1113 return nullptr; 1114 } 1115 1116 isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0)); 1117 1118 for (long i = 0; i < Min.dim(isl::dim::set); i++) { 1119 if (i > 0) { 1120 isl::pw_aff Bound_I = 1121 isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1)); 1122 isl::ast_expr BExpr = Build.expr_from(Bound_I); 1123 Result = Result.mul(BExpr); 1124 } 1125 isl::pw_aff DimMin = Min.dim_min(i); 1126 isl::ast_expr MExpr = Build.expr_from(DimMin); 1127 Result = Result.add(MExpr); 1128 } 1129 1130 return ExprBuilder.create(Result.release()); 1131 } 1132 1133 Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array, 1134 ScopArrayInfo *ArrayInfo) { 1135 assert(ManagedMemory && "Only used when you wish to get a host " 1136 "pointer for sending data to the kernel, " 1137 "with managed memory"); 1138 std::map<ScopArrayInfo *, Value *>::iterator it; 1139 it = DeviceAllocations.find(ArrayInfo); 1140 assert(it != DeviceAllocations.end() && 1141 "Device array expected to be available"); 1142 return it->second; 1143 } 1144 1145 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 1146 enum DataDirection Direction) { 1147 assert(!ManagedMemory && "Managed memory needs no data transfers"); 1148 isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 1149 isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 1150 isl_id *Id = isl_ast_expr_get_id(Arg); 1151 auto Array = (gpu_array_info *)isl_id_get_user(Id); 1152 auto ScopArray = (ScopArrayInfo *)(Array->user); 1153 1154 Value *Size = getArraySize(Array); 1155 Value *Offset = getArrayOffset(Array); 1156 Value *DevPtr = DeviceAllocations[ScopArray]; 1157 1158 Value *HostPtr; 1159 1160 if (gpu_array_is_scalar(Array)) 1161 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1162 else 1163 HostPtr = ScopArray->getBasePtr(); 1164 HostPtr = getLatestValue(HostPtr); 1165 1166 if (Offset) { 1167 HostPtr = Builder.CreatePointerCast( 1168 HostPtr, ScopArray->getElementType()->getPointerTo()); 1169 HostPtr = Builder.CreateGEP(HostPtr, Offset); 1170 } 1171 1172 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1173 1174 if (Offset) { 1175 Size = Builder.CreateSub( 1176 Size, Builder.CreateMul( 1177 Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1178 } 1179 1180 if (Direction == HOST_TO_DEVICE) 1181 createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 1182 else 1183 createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 1184 1185 isl_id_free(Id); 1186 isl_ast_expr_free(Arg); 1187 isl_ast_expr_free(Expr); 1188 isl_ast_node_free(TransferStmt); 1189 } 1190 1191 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 1192 isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 1193 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1194 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1195 isl_id_free(Id); 1196 isl_ast_expr_free(StmtExpr); 1197 1198 const char *Str = isl_id_get_name(Id); 1199 if (!strcmp(Str, "kernel")) { 1200 createKernel(UserStmt); 1201 isl_ast_expr_free(Expr); 1202 return; 1203 } 1204 if (!strcmp(Str, "init_device")) { 1205 initializeAfterRTH(); 1206 isl_ast_node_free(UserStmt); 1207 isl_ast_expr_free(Expr); 1208 return; 1209 } 1210 if (!strcmp(Str, "clear_device")) { 1211 finalize(); 1212 isl_ast_node_free(UserStmt); 1213 isl_ast_expr_free(Expr); 1214 return; 1215 } 1216 if (isPrefix(Str, "to_device")) { 1217 if (!ManagedMemory) 1218 createDataTransfer(UserStmt, HOST_TO_DEVICE); 1219 else 1220 isl_ast_node_free(UserStmt); 1221 1222 isl_ast_expr_free(Expr); 1223 return; 1224 } 1225 1226 if (isPrefix(Str, "from_device")) { 1227 if (!ManagedMemory) { 1228 createDataTransfer(UserStmt, DEVICE_TO_HOST); 1229 } else { 1230 createCallSynchronizeDevice(); 1231 isl_ast_node_free(UserStmt); 1232 } 1233 isl_ast_expr_free(Expr); 1234 return; 1235 } 1236 1237 isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 1238 struct ppcg_kernel_stmt *KernelStmt = 1239 (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 1240 isl_id_free(Anno); 1241 1242 switch (KernelStmt->type) { 1243 case ppcg_kernel_domain: 1244 createScopStmt(Expr, KernelStmt); 1245 isl_ast_node_free(UserStmt); 1246 return; 1247 case ppcg_kernel_copy: 1248 createKernelCopy(KernelStmt); 1249 isl_ast_expr_free(Expr); 1250 isl_ast_node_free(UserStmt); 1251 return; 1252 case ppcg_kernel_sync: 1253 createKernelSync(); 1254 isl_ast_expr_free(Expr); 1255 isl_ast_node_free(UserStmt); 1256 return; 1257 } 1258 1259 isl_ast_expr_free(Expr); 1260 isl_ast_node_free(UserStmt); 1261 return; 1262 } 1263 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1264 isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1265 LocalIndex = isl_ast_expr_address_of(LocalIndex); 1266 Value *LocalAddr = ExprBuilder.create(LocalIndex); 1267 isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1268 Index = isl_ast_expr_address_of(Index); 1269 Value *GlobalAddr = ExprBuilder.create(Index); 1270 1271 if (KernelStmt->u.c.read) { 1272 LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1273 Builder.CreateStore(Load, LocalAddr); 1274 } else { 1275 LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1276 Builder.CreateStore(Load, GlobalAddr); 1277 } 1278 } 1279 1280 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1281 ppcg_kernel_stmt *KernelStmt) { 1282 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1283 isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1284 1285 LoopToScevMapT LTS; 1286 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1287 1288 createSubstitutions(Expr, Stmt, LTS); 1289 1290 if (Stmt->isBlockStmt()) 1291 BlockGen.copyStmt(*Stmt, LTS, Indexes); 1292 else 1293 RegionGen.copyStmt(*Stmt, LTS, Indexes); 1294 } 1295 1296 void GPUNodeBuilder::createKernelSync() { 1297 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1298 const char *SpirName = "__gen_ocl_barrier_global"; 1299 1300 Function *Sync; 1301 1302 switch (Arch) { 1303 case GPUArch::SPIR64: 1304 case GPUArch::SPIR32: 1305 Sync = M->getFunction(SpirName); 1306 1307 // If Sync is not available, declare it. 1308 if (!Sync) { 1309 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 1310 std::vector<Type *> Args; 1311 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 1312 Sync = Function::Create(Ty, Linkage, SpirName, M); 1313 Sync->setCallingConv(CallingConv::SPIR_FUNC); 1314 } 1315 break; 1316 case GPUArch::NVPTX64: 1317 Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 1318 break; 1319 } 1320 1321 Builder.CreateCall(Sync, {}); 1322 } 1323 1324 /// Collect llvm::Values referenced from @p Node 1325 /// 1326 /// This function only applies to isl_ast_nodes that are user_nodes referring 1327 /// to a ScopStmt. All other node types are ignore. 1328 /// 1329 /// @param Node The node to collect references for. 1330 /// @param User A user pointer used as storage for the data that is collected. 1331 /// 1332 /// @returns isl_bool_true if data could be collected successfully. 1333 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1334 if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1335 return isl_bool_true; 1336 1337 isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1338 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1339 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1340 const char *Str = isl_id_get_name(Id); 1341 isl_id_free(Id); 1342 isl_ast_expr_free(StmtExpr); 1343 isl_ast_expr_free(Expr); 1344 1345 if (!isPrefix(Str, "Stmt")) 1346 return isl_bool_true; 1347 1348 Id = isl_ast_node_get_annotation(Node); 1349 auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1350 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1351 isl_id_free(Id); 1352 1353 addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1354 1355 return isl_bool_true; 1356 } 1357 1358 /// A list of functions that are available in NVIDIA's libdevice. 1359 const std::set<std::string> CUDALibDeviceFunctions = { 1360 "exp", "expf", "expl", "cos", "cosf", 1361 "sqrt", "sqrtf", "copysign", "copysignf", "copysignl"}; 1362 1363 /// Return the corresponding CUDA libdevice function name for @p F. 1364 /// 1365 /// Return "" if we are not compiling for CUDA. 1366 std::string getCUDALibDeviceFuntion(Function *F) { 1367 if (CUDALibDeviceFunctions.count(F->getName())) 1368 return std::string("__nv_") + std::string(F->getName()); 1369 1370 return ""; 1371 } 1372 1373 /// Check if F is a function that we can code-generate in a GPU kernel. 1374 static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) { 1375 assert(F && "F is an invalid pointer"); 1376 // We string compare against the name of the function to allow 1377 // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 1378 // "llvm.copysign". 1379 const StringRef Name = F->getName(); 1380 1381 if (AllowLibDevice && getCUDALibDeviceFuntion(F).length() > 0) 1382 return true; 1383 1384 return F->isIntrinsic() && 1385 (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 1386 Name.startswith("llvm.copysign")); 1387 } 1388 1389 /// Do not take `Function` as a subtree value. 1390 /// 1391 /// We try to take the reference of all subtree values and pass them along 1392 /// to the kernel from the host. Taking an address of any function and 1393 /// trying to pass along is nonsensical. Only allow `Value`s that are not 1394 /// `Function`s. 1395 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1396 1397 /// Return `Function`s from `RawSubtreeValues`. 1398 static SetVector<Function *> 1399 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues, 1400 bool AllowCUDALibDevice) { 1401 SetVector<Function *> SubtreeFunctions; 1402 for (Value *It : RawSubtreeValues) { 1403 Function *F = dyn_cast<Function>(It); 1404 if (F) { 1405 assert(isValidFunctionInKernel(F, AllowCUDALibDevice) && 1406 "Code should have bailed out by " 1407 "this point if an invalid function " 1408 "were present in a kernel."); 1409 SubtreeFunctions.insert(F); 1410 } 1411 } 1412 return SubtreeFunctions; 1413 } 1414 1415 std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>> 1416 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1417 SetVector<Value *> SubtreeValues; 1418 SetVector<const SCEV *> SCEVs; 1419 SetVector<const Loop *> Loops; 1420 SubtreeReferences References = { 1421 LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1422 1423 for (const auto &I : IDToValue) 1424 SubtreeValues.insert(I.second); 1425 1426 // NOTE: this is populated in IslNodeBuilder::addParameters 1427 // See [Code generation of induction variables of loops outside Scops]. 1428 for (const auto &I : OutsideLoopIterations) 1429 SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue()); 1430 1431 isl_ast_node_foreach_descendant_top_down( 1432 Kernel->tree, collectReferencesInGPUStmt, &References); 1433 1434 for (const SCEV *Expr : SCEVs) { 1435 findValues(Expr, SE, SubtreeValues); 1436 findLoops(Expr, Loops); 1437 } 1438 1439 Loops.remove_if([this](const Loop *L) { 1440 return S.contains(L) || L->contains(S.getEntry()); 1441 }); 1442 1443 for (auto &SAI : S.arrays()) 1444 SubtreeValues.remove(SAI->getBasePtr()); 1445 1446 isl_space *Space = S.getParamSpace(); 1447 for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1448 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1449 assert(IDToValue.count(Id)); 1450 Value *Val = IDToValue[Id]; 1451 SubtreeValues.remove(Val); 1452 isl_id_free(Id); 1453 } 1454 isl_space_free(Space); 1455 1456 for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1457 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1458 assert(IDToValue.count(Id)); 1459 Value *Val = IDToValue[Id]; 1460 SubtreeValues.remove(Val); 1461 isl_id_free(Id); 1462 } 1463 1464 // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1465 // SubtreeValues. This is important, because we should not lose any 1466 // SubtreeValues in the process of constructing the 1467 // "ValidSubtree{Values, Functions} sets. Nor should the set 1468 // ValidSubtree{Values, Functions} have any common element. 1469 auto ValidSubtreeValuesIt = 1470 make_filter_range(SubtreeValues, isValidSubtreeValue); 1471 SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1472 ValidSubtreeValuesIt.end()); 1473 1474 bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64; 1475 1476 SetVector<Function *> ValidSubtreeFunctions( 1477 getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice)); 1478 1479 // @see IslNodeBuilder::getReferencesInSubtree 1480 SetVector<Value *> ReplacedValues; 1481 for (Value *V : ValidSubtreeValues) { 1482 auto It = ValueMap.find(V); 1483 if (It == ValueMap.end()) 1484 ReplacedValues.insert(V); 1485 else 1486 ReplacedValues.insert(It->second); 1487 } 1488 return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops); 1489 } 1490 1491 void GPUNodeBuilder::clearDominators(Function *F) { 1492 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 1493 std::vector<BasicBlock *> Nodes; 1494 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 1495 Nodes.push_back(I->getBlock()); 1496 1497 for (BasicBlock *BB : Nodes) 1498 DT.eraseNode(BB); 1499 } 1500 1501 void GPUNodeBuilder::clearScalarEvolution(Function *F) { 1502 for (BasicBlock &BB : *F) { 1503 Loop *L = LI.getLoopFor(&BB); 1504 if (L) 1505 SE.forgetLoop(L); 1506 } 1507 } 1508 1509 void GPUNodeBuilder::clearLoops(Function *F) { 1510 for (BasicBlock &BB : *F) { 1511 Loop *L = LI.getLoopFor(&BB); 1512 if (L) 1513 SE.forgetLoop(L); 1514 LI.removeBlock(&BB); 1515 } 1516 } 1517 1518 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 1519 std::vector<Value *> Sizes; 1520 isl::ast_build Context = 1521 isl::ast_build::from_context(isl::manage(S.getContext())); 1522 1523 isl::multi_pw_aff GridSizePwAffs = 1524 isl::manage(isl_multi_pw_aff_copy(Kernel->grid_size)); 1525 for (long i = 0; i < Kernel->n_grid; i++) { 1526 isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i); 1527 isl::ast_expr GridSize = Context.expr_from(Size); 1528 Value *Res = ExprBuilder.create(GridSize.release()); 1529 Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 1530 Sizes.push_back(Res); 1531 } 1532 1533 for (long i = Kernel->n_grid; i < 3; i++) 1534 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1535 1536 return std::make_tuple(Sizes[0], Sizes[1]); 1537 } 1538 1539 std::tuple<Value *, Value *, Value *> 1540 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 1541 std::vector<Value *> Sizes; 1542 1543 for (long i = 0; i < Kernel->n_block; i++) { 1544 Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 1545 Sizes.push_back(Res); 1546 } 1547 1548 for (long i = Kernel->n_block; i < 3; i++) 1549 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1550 1551 return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 1552 } 1553 1554 void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1555 Instruction *Param, int Index) { 1556 Value *Slot = Builder.CreateGEP( 1557 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1558 Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1559 Builder.CreateStore(ParamTyped, Slot); 1560 } 1561 1562 Value * 1563 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 1564 SetVector<Value *> SubtreeValues) { 1565 const int NumArgs = F->arg_size(); 1566 std::vector<int> ArgSizes(NumArgs); 1567 1568 Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 1569 1570 BasicBlock *EntryBlock = 1571 &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1572 auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 1573 std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 1574 Instruction *Parameters = new AllocaInst( 1575 ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 1576 1577 int Index = 0; 1578 for (long i = 0; i < Prog->n_array; i++) { 1579 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1580 continue; 1581 1582 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1583 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1584 1585 ArgSizes[Index] = SAI->getElemSizeInBytes(); 1586 1587 Value *DevArray = nullptr; 1588 if (ManagedMemory) { 1589 DevArray = getManagedDeviceArray(&Prog->array[i], 1590 const_cast<ScopArrayInfo *>(SAI)); 1591 } else { 1592 DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 1593 DevArray = createCallGetDevicePtr(DevArray); 1594 } 1595 assert(DevArray != nullptr && "Array to be offloaded to device not " 1596 "initialized"); 1597 Value *Offset = getArrayOffset(&Prog->array[i]); 1598 1599 if (Offset) { 1600 DevArray = Builder.CreatePointerCast( 1601 DevArray, SAI->getElementType()->getPointerTo()); 1602 DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1603 DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1604 } 1605 Value *Slot = Builder.CreateGEP( 1606 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1607 1608 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1609 Value *ValPtr = nullptr; 1610 if (ManagedMemory) 1611 ValPtr = DevArray; 1612 else 1613 ValPtr = BlockGen.getOrCreateAlloca(SAI); 1614 1615 assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1616 " to be stored into Parameters"); 1617 Value *ValPtrCast = 1618 Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1619 Builder.CreateStore(ValPtrCast, Slot); 1620 } else { 1621 Instruction *Param = 1622 new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 1623 Launch + "_param_" + std::to_string(Index), 1624 EntryBlock->getTerminator()); 1625 Builder.CreateStore(DevArray, Param); 1626 Value *ParamTyped = 1627 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1628 Builder.CreateStore(ParamTyped, Slot); 1629 } 1630 Index++; 1631 } 1632 1633 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1634 1635 for (long i = 0; i < NumHostIters; i++) { 1636 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1637 Value *Val = IDToValue[Id]; 1638 isl_id_free(Id); 1639 1640 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1641 1642 Instruction *Param = 1643 new AllocaInst(Val->getType(), AddressSpace, 1644 Launch + "_param_" + std::to_string(Index), 1645 EntryBlock->getTerminator()); 1646 Builder.CreateStore(Val, Param); 1647 insertStoreParameter(Parameters, Param, Index); 1648 Index++; 1649 } 1650 1651 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1652 1653 for (long i = 0; i < NumVars; i++) { 1654 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1655 Value *Val = IDToValue[Id]; 1656 if (ValueMap.count(Val)) 1657 Val = ValueMap[Val]; 1658 isl_id_free(Id); 1659 1660 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1661 1662 Instruction *Param = 1663 new AllocaInst(Val->getType(), AddressSpace, 1664 Launch + "_param_" + std::to_string(Index), 1665 EntryBlock->getTerminator()); 1666 Builder.CreateStore(Val, Param); 1667 insertStoreParameter(Parameters, Param, Index); 1668 Index++; 1669 } 1670 1671 for (auto Val : SubtreeValues) { 1672 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1673 1674 Instruction *Param = 1675 new AllocaInst(Val->getType(), AddressSpace, 1676 Launch + "_param_" + std::to_string(Index), 1677 EntryBlock->getTerminator()); 1678 Builder.CreateStore(Val, Param); 1679 insertStoreParameter(Parameters, Param, Index); 1680 Index++; 1681 } 1682 1683 for (int i = 0; i < NumArgs; i++) { 1684 Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1685 Instruction *Param = 1686 new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1687 Launch + "_param_size_" + std::to_string(i), 1688 EntryBlock->getTerminator()); 1689 Builder.CreateStore(Val, Param); 1690 insertStoreParameter(Parameters, Param, Index); 1691 Index++; 1692 } 1693 1694 auto Location = EntryBlock->getTerminator(); 1695 return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 1696 Launch + "_params_i8ptr", Location); 1697 } 1698 1699 void GPUNodeBuilder::setupKernelSubtreeFunctions( 1700 SetVector<Function *> SubtreeFunctions) { 1701 for (auto Fn : SubtreeFunctions) { 1702 const std::string ClonedFnName = Fn->getName(); 1703 Function *Clone = GPUModule->getFunction(ClonedFnName); 1704 if (!Clone) 1705 Clone = 1706 Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1707 ClonedFnName, GPUModule.get()); 1708 assert(Clone && "Expected cloned function to be initialized."); 1709 assert(ValueMap.find(Fn) == ValueMap.end() && 1710 "Fn already present in ValueMap"); 1711 ValueMap[Fn] = Clone; 1712 } 1713 } 1714 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 1715 isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 1716 ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 1717 isl_id_free(Id); 1718 isl_ast_node_free(KernelStmt); 1719 1720 if (Kernel->n_grid > 1) 1721 DeepestParallel = 1722 std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1723 else 1724 DeepestSequential = 1725 std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1726 1727 Value *BlockDimX, *BlockDimY, *BlockDimZ; 1728 std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1729 1730 SetVector<Value *> SubtreeValues; 1731 SetVector<Function *> SubtreeFunctions; 1732 SetVector<const Loop *> Loops; 1733 std::tie(SubtreeValues, SubtreeFunctions, Loops) = 1734 getReferencesInKernel(Kernel); 1735 1736 assert(Kernel->tree && "Device AST of kernel node is empty"); 1737 1738 Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1739 IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1740 ValueMapT HostValueMap = ValueMap; 1741 BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1742 ScalarMap.clear(); 1743 1744 // Create for all loops we depend on values that contain the current loop 1745 // iteration. These values are necessary to generate code for SCEVs that 1746 // depend on such loops. As a result we need to pass them to the subfunction. 1747 for (const Loop *L : Loops) { 1748 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1749 SE.getUnknown(Builder.getInt64(1)), 1750 L, SCEV::FlagAnyWrap); 1751 Value *V = generateSCEV(OuterLIV); 1752 OutsideLoopIterations[L] = SE.getUnknown(V); 1753 SubtreeValues.insert(V); 1754 } 1755 1756 createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1757 setupKernelSubtreeFunctions(SubtreeFunctions); 1758 1759 create(isl_ast_node_copy(Kernel->tree)); 1760 1761 finalizeKernelArguments(Kernel); 1762 Function *F = Builder.GetInsertBlock()->getParent(); 1763 if (Arch == GPUArch::NVPTX64) 1764 addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 1765 clearDominators(F); 1766 clearScalarEvolution(F); 1767 clearLoops(F); 1768 1769 IDToValue = HostIDs; 1770 1771 ValueMap = std::move(HostValueMap); 1772 ScalarMap = std::move(HostScalarMap); 1773 EscapeMap.clear(); 1774 IDToSAI.clear(); 1775 Annotator.resetAlternativeAliasBases(); 1776 for (auto &BasePtr : LocalArrays) 1777 S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 1778 LocalArrays.clear(); 1779 1780 std::string ASMString = finalizeKernelFunction(); 1781 Builder.SetInsertPoint(&HostInsertPoint); 1782 Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 1783 1784 std::string Name = getKernelFuncName(Kernel->id); 1785 Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 1786 Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 1787 Value *GPUKernel = createCallGetKernel(KernelString, NameString); 1788 1789 Value *GridDimX, *GridDimY; 1790 std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 1791 1792 createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 1793 BlockDimZ, Parameters); 1794 createCallFreeKernel(GPUKernel); 1795 1796 for (auto Id : KernelIds) 1797 isl_id_free(Id); 1798 1799 KernelIds.clear(); 1800 } 1801 1802 /// Compute the DataLayout string for the NVPTX backend. 1803 /// 1804 /// @param is64Bit Are we looking for a 64 bit architecture? 1805 static std::string computeNVPTXDataLayout(bool is64Bit) { 1806 std::string Ret = ""; 1807 1808 if (!is64Bit) { 1809 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1810 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1811 "64-v128:128:128-n16:32:64"; 1812 } else { 1813 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1814 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1815 "64-v128:128:128-n16:32:64"; 1816 } 1817 1818 return Ret; 1819 } 1820 1821 /// Compute the DataLayout string for a SPIR kernel. 1822 /// 1823 /// @param is64Bit Are we looking for a 64 bit architecture? 1824 static std::string computeSPIRDataLayout(bool is64Bit) { 1825 std::string Ret = ""; 1826 1827 if (!is64Bit) { 1828 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1829 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1830 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1831 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1832 } else { 1833 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1834 "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:" 1835 "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:" 1836 "256:256-v256:256:256-v512:512:512-v1024:1024:1024"; 1837 } 1838 1839 return Ret; 1840 } 1841 1842 Function * 1843 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1844 SetVector<Value *> &SubtreeValues) { 1845 std::vector<Type *> Args; 1846 std::string Identifier = getKernelFuncName(Kernel->id); 1847 1848 std::vector<Metadata *> MemoryType; 1849 1850 for (long i = 0; i < Prog->n_array; i++) { 1851 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1852 continue; 1853 1854 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1855 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1856 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id)); 1857 Args.push_back(SAI->getElementType()); 1858 MemoryType.push_back( 1859 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1860 } else { 1861 static const int UseGlobalMemory = 1; 1862 Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 1863 MemoryType.push_back( 1864 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1))); 1865 } 1866 } 1867 1868 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1869 1870 for (long i = 0; i < NumHostIters; i++) { 1871 Args.push_back(Builder.getInt64Ty()); 1872 MemoryType.push_back( 1873 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1874 } 1875 1876 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1877 1878 for (long i = 0; i < NumVars; i++) { 1879 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1880 Value *Val = IDToValue[Id]; 1881 isl_id_free(Id); 1882 Args.push_back(Val->getType()); 1883 MemoryType.push_back( 1884 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1885 } 1886 1887 for (auto *V : SubtreeValues) { 1888 Args.push_back(V->getType()); 1889 MemoryType.push_back( 1890 ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0))); 1891 } 1892 1893 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1894 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1895 GPUModule.get()); 1896 1897 std::vector<Metadata *> EmptyStrings; 1898 1899 for (unsigned int i = 0; i < MemoryType.size(); i++) { 1900 EmptyStrings.push_back(MDString::get(FN->getContext(), "")); 1901 } 1902 1903 if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) { 1904 FN->setMetadata("kernel_arg_addr_space", 1905 MDNode::get(FN->getContext(), MemoryType)); 1906 FN->setMetadata("kernel_arg_name", 1907 MDNode::get(FN->getContext(), EmptyStrings)); 1908 FN->setMetadata("kernel_arg_access_qual", 1909 MDNode::get(FN->getContext(), EmptyStrings)); 1910 FN->setMetadata("kernel_arg_type", 1911 MDNode::get(FN->getContext(), EmptyStrings)); 1912 FN->setMetadata("kernel_arg_type_qual", 1913 MDNode::get(FN->getContext(), EmptyStrings)); 1914 FN->setMetadata("kernel_arg_base_type", 1915 MDNode::get(FN->getContext(), EmptyStrings)); 1916 } 1917 1918 switch (Arch) { 1919 case GPUArch::NVPTX64: 1920 FN->setCallingConv(CallingConv::PTX_Kernel); 1921 break; 1922 case GPUArch::SPIR32: 1923 case GPUArch::SPIR64: 1924 FN->setCallingConv(CallingConv::SPIR_KERNEL); 1925 break; 1926 } 1927 1928 auto Arg = FN->arg_begin(); 1929 for (long i = 0; i < Kernel->n_array; i++) { 1930 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1931 continue; 1932 1933 Arg->setName(Kernel->array[i].array->name); 1934 1935 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1936 const ScopArrayInfo *SAI = 1937 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 1938 Type *EleTy = SAI->getElementType(); 1939 Value *Val = &*Arg; 1940 SmallVector<const SCEV *, 4> Sizes; 1941 isl_ast_build *Build = 1942 isl_ast_build_from_context(isl_set_copy(Prog->context)); 1943 Sizes.push_back(nullptr); 1944 for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1945 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1946 Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1947 auto V = ExprBuilder.create(DimSize); 1948 Sizes.push_back(SE.getSCEV(V)); 1949 } 1950 const ScopArrayInfo *SAIRep = 1951 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 1952 LocalArrays.push_back(Val); 1953 1954 isl_ast_build_free(Build); 1955 KernelIds.push_back(Id); 1956 IDToSAI[Id] = SAIRep; 1957 Arg++; 1958 } 1959 1960 for (long i = 0; i < NumHostIters; i++) { 1961 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1962 Arg->setName(isl_id_get_name(Id)); 1963 IDToValue[Id] = &*Arg; 1964 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1965 Arg++; 1966 } 1967 1968 for (long i = 0; i < NumVars; i++) { 1969 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1970 Arg->setName(isl_id_get_name(Id)); 1971 Value *Val = IDToValue[Id]; 1972 ValueMap[Val] = &*Arg; 1973 IDToValue[Id] = &*Arg; 1974 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1975 Arg++; 1976 } 1977 1978 for (auto *V : SubtreeValues) { 1979 Arg->setName(V->getName()); 1980 ValueMap[V] = &*Arg; 1981 Arg++; 1982 } 1983 1984 return FN; 1985 } 1986 1987 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1988 Intrinsic::ID IntrinsicsBID[2]; 1989 Intrinsic::ID IntrinsicsTID[3]; 1990 1991 switch (Arch) { 1992 case GPUArch::SPIR64: 1993 case GPUArch::SPIR32: 1994 llvm_unreachable("Cannot generate NVVM intrinsics for SPIR"); 1995 case GPUArch::NVPTX64: 1996 IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 1997 IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 1998 1999 IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 2000 IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 2001 IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 2002 break; 2003 } 2004 2005 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 2006 std::string Name = isl_id_get_name(Id); 2007 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2008 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 2009 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 2010 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2011 IDToValue[Id] = Val; 2012 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2013 }; 2014 2015 for (int i = 0; i < Kernel->n_grid; ++i) { 2016 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 2017 addId(Id, IntrinsicsBID[i]); 2018 } 2019 2020 for (int i = 0; i < Kernel->n_block; ++i) { 2021 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 2022 addId(Id, IntrinsicsTID[i]); 2023 } 2024 } 2025 2026 void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel) { 2027 const char *GroupName[3] = {"__gen_ocl_get_group_id0", 2028 "__gen_ocl_get_group_id1", 2029 "__gen_ocl_get_group_id2"}; 2030 2031 const char *LocalName[3] = {"__gen_ocl_get_local_id0", 2032 "__gen_ocl_get_local_id1", 2033 "__gen_ocl_get_local_id2"}; 2034 2035 auto createFunc = [this](const char *Name, __isl_take isl_id *Id) mutable { 2036 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2037 Function *FN = M->getFunction(Name); 2038 2039 // If FN is not available, declare it. 2040 if (!FN) { 2041 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 2042 std::vector<Type *> Args; 2043 FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), Args, false); 2044 FN = Function::Create(Ty, Linkage, Name, M); 2045 FN->setCallingConv(CallingConv::SPIR_FUNC); 2046 } 2047 2048 Value *Val = Builder.CreateCall(FN, {}); 2049 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 2050 IDToValue[Id] = Val; 2051 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 2052 }; 2053 2054 for (int i = 0; i < Kernel->n_grid; ++i) 2055 createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i)); 2056 2057 for (int i = 0; i < Kernel->n_block; ++i) 2058 createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i)); 2059 } 2060 2061 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 2062 auto Arg = FN->arg_begin(); 2063 for (long i = 0; i < Kernel->n_array; i++) { 2064 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2065 continue; 2066 2067 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2068 const ScopArrayInfo *SAI = 2069 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 2070 isl_id_free(Id); 2071 2072 if (SAI->getNumberOfDimensions() > 0) { 2073 Arg++; 2074 continue; 2075 } 2076 2077 Value *Val = &*Arg; 2078 2079 if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 2080 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2081 Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 2082 Val = Builder.CreateLoad(TypedArgPtr); 2083 } 2084 2085 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2086 Builder.CreateStore(Val, Alloca); 2087 2088 Arg++; 2089 } 2090 } 2091 2092 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 2093 auto *FN = Builder.GetInsertBlock()->getParent(); 2094 auto Arg = FN->arg_begin(); 2095 2096 bool StoredScalar = false; 2097 for (long i = 0; i < Kernel->n_array; i++) { 2098 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 2099 continue; 2100 2101 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 2102 const ScopArrayInfo *SAI = 2103 ScopArrayInfo::getFromId(isl::manage(isl_id_copy(Id))); 2104 isl_id_free(Id); 2105 2106 if (SAI->getNumberOfDimensions() > 0) { 2107 Arg++; 2108 continue; 2109 } 2110 2111 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 2112 Arg++; 2113 continue; 2114 } 2115 2116 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 2117 Value *ArgPtr = &*Arg; 2118 Type *TypePtr = SAI->getElementType()->getPointerTo(); 2119 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 2120 Value *Val = Builder.CreateLoad(Alloca); 2121 Builder.CreateStore(Val, TypedArgPtr); 2122 StoredScalar = true; 2123 2124 Arg++; 2125 } 2126 2127 if (StoredScalar) { 2128 /// In case more than one thread contains scalar stores, the generated 2129 /// code might be incorrect, if we only store at the end of the kernel. 2130 /// To support this case we need to store these scalars back at each 2131 /// memory store or at least before each kernel barrier. 2132 if (Kernel->n_block != 0 || Kernel->n_grid != 0) { 2133 BuildSuccessful = 0; 2134 DEBUG( 2135 dbgs() << getUniqueScopName(&S) 2136 << " has a store to a scalar value that" 2137 " would be undefined to run in parallel. Bailing out.\n";); 2138 } 2139 } 2140 } 2141 2142 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 2143 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 2144 2145 for (int i = 0; i < Kernel->n_var; ++i) { 2146 struct ppcg_kernel_var &Var = Kernel->var[i]; 2147 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 2148 Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType(); 2149 2150 Type *ArrayTy = EleTy; 2151 SmallVector<const SCEV *, 4> Sizes; 2152 2153 Sizes.push_back(nullptr); 2154 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 2155 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2156 long Bound = isl_val_get_num_si(Val); 2157 isl_val_free(Val); 2158 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 2159 } 2160 2161 for (int j = Var.array->n_index - 1; j >= 0; --j) { 2162 isl_val *Val = isl_vec_get_element_val(Var.size, j); 2163 long Bound = isl_val_get_num_si(Val); 2164 isl_val_free(Val); 2165 ArrayTy = ArrayType::get(ArrayTy, Bound); 2166 } 2167 2168 const ScopArrayInfo *SAI; 2169 Value *Allocation; 2170 if (Var.type == ppcg_access_shared) { 2171 auto GlobalVar = new GlobalVariable( 2172 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 2173 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 2174 GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 2175 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 2176 2177 Allocation = GlobalVar; 2178 } else if (Var.type == ppcg_access_private) { 2179 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 2180 } else { 2181 llvm_unreachable("unknown variable type"); 2182 } 2183 SAI = 2184 S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 2185 Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 2186 IDToValue[Id] = Allocation; 2187 LocalArrays.push_back(Allocation); 2188 KernelIds.push_back(Id); 2189 IDToSAI[Id] = SAI; 2190 } 2191 } 2192 2193 void GPUNodeBuilder::createKernelFunction( 2194 ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 2195 SetVector<Function *> &SubtreeFunctions) { 2196 std::string Identifier = getKernelFuncName(Kernel->id); 2197 GPUModule.reset(new Module(Identifier, Builder.getContext())); 2198 2199 switch (Arch) { 2200 case GPUArch::NVPTX64: 2201 if (Runtime == GPURuntime::CUDA) 2202 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2203 else if (Runtime == GPURuntime::OpenCL) 2204 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 2205 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 2206 break; 2207 case GPUArch::SPIR32: 2208 GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown")); 2209 GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */)); 2210 break; 2211 case GPUArch::SPIR64: 2212 GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown")); 2213 GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */)); 2214 break; 2215 } 2216 2217 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 2218 2219 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 2220 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 2221 2222 DT.addNewBlock(EntryBlock, PrevBlock); 2223 2224 Builder.SetInsertPoint(EntryBlock); 2225 Builder.CreateRetVoid(); 2226 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2227 2228 ScopDetection::markFunctionAsInvalid(FN); 2229 2230 prepareKernelArguments(Kernel, FN); 2231 createKernelVariables(Kernel, FN); 2232 2233 switch (Arch) { 2234 case GPUArch::NVPTX64: 2235 insertKernelIntrinsics(Kernel); 2236 break; 2237 case GPUArch::SPIR32: 2238 case GPUArch::SPIR64: 2239 insertKernelCallsSPIR(Kernel); 2240 break; 2241 } 2242 } 2243 2244 std::string GPUNodeBuilder::createKernelASM() { 2245 llvm::Triple GPUTriple; 2246 2247 switch (Arch) { 2248 case GPUArch::NVPTX64: 2249 switch (Runtime) { 2250 case GPURuntime::CUDA: 2251 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 2252 break; 2253 case GPURuntime::OpenCL: 2254 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 2255 break; 2256 } 2257 break; 2258 case GPUArch::SPIR64: 2259 case GPUArch::SPIR32: 2260 std::string SPIRAssembly; 2261 raw_string_ostream IROstream(SPIRAssembly); 2262 IROstream << *GPUModule; 2263 IROstream.flush(); 2264 return SPIRAssembly; 2265 } 2266 2267 std::string ErrMsg; 2268 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 2269 2270 if (!GPUTarget) { 2271 errs() << ErrMsg << "\n"; 2272 return ""; 2273 } 2274 2275 TargetOptions Options; 2276 Options.UnsafeFPMath = FastMath; 2277 2278 std::string subtarget; 2279 2280 switch (Arch) { 2281 case GPUArch::NVPTX64: 2282 subtarget = CudaVersion; 2283 break; 2284 case GPUArch::SPIR32: 2285 case GPUArch::SPIR64: 2286 llvm_unreachable("No subtarget for SPIR architecture"); 2287 } 2288 2289 std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 2290 GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 2291 2292 SmallString<0> ASMString; 2293 raw_svector_ostream ASMStream(ASMString); 2294 llvm::legacy::PassManager PM; 2295 2296 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 2297 2298 if (TargetM->addPassesToEmitFile( 2299 PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 2300 errs() << "The target does not support generation of this file type!\n"; 2301 return ""; 2302 } 2303 2304 PM.run(*GPUModule); 2305 2306 return ASMStream.str(); 2307 } 2308 2309 bool GPUNodeBuilder::requiresCUDALibDevice() { 2310 bool RequiresLibDevice = false; 2311 for (Function &F : GPUModule->functions()) { 2312 if (!F.isDeclaration()) 2313 continue; 2314 2315 std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(&F); 2316 if (CUDALibDeviceFunc.length() != 0) { 2317 F.setName(CUDALibDeviceFunc); 2318 RequiresLibDevice = true; 2319 } 2320 } 2321 2322 return RequiresLibDevice; 2323 } 2324 2325 void GPUNodeBuilder::addCUDALibDevice() { 2326 if (Arch != GPUArch::NVPTX64) 2327 return; 2328 2329 if (requiresCUDALibDevice()) { 2330 SMDiagnostic Error; 2331 2332 errs() << CUDALibDevice << "\n"; 2333 auto LibDeviceModule = 2334 parseIRFile(CUDALibDevice, Error, GPUModule->getContext()); 2335 2336 if (!LibDeviceModule) { 2337 BuildSuccessful = false; 2338 report_fatal_error("Could not find or load libdevice. Skipping GPU " 2339 "kernel generation. Please set -polly-acc-libdevice " 2340 "accordingly.\n"); 2341 return; 2342 } 2343 2344 Linker L(*GPUModule); 2345 2346 // Set an nvptx64 target triple to avoid linker warnings. The original 2347 // triple of the libdevice files are nvptx-unknown-unknown. 2348 LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2349 L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded); 2350 } 2351 } 2352 2353 std::string GPUNodeBuilder::finalizeKernelFunction() { 2354 2355 if (verifyModule(*GPUModule)) { 2356 DEBUG(dbgs() << "verifyModule failed on module:\n"; 2357 GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2358 DEBUG(dbgs() << "verifyModule Error:\n"; 2359 verifyModule(*GPUModule, &dbgs());); 2360 2361 if (FailOnVerifyModuleFailure) 2362 llvm_unreachable("VerifyModule failed."); 2363 2364 BuildSuccessful = false; 2365 return ""; 2366 } 2367 2368 addCUDALibDevice(); 2369 2370 if (DumpKernelIR) 2371 outs() << *GPUModule << "\n"; 2372 2373 if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) { 2374 // Optimize module. 2375 llvm::legacy::PassManager OptPasses; 2376 PassManagerBuilder PassBuilder; 2377 PassBuilder.OptLevel = 3; 2378 PassBuilder.SizeLevel = 0; 2379 PassBuilder.populateModulePassManager(OptPasses); 2380 OptPasses.run(*GPUModule); 2381 } 2382 2383 std::string Assembly = createKernelASM(); 2384 2385 if (DumpKernelASM) 2386 outs() << Assembly << "\n"; 2387 2388 GPUModule.release(); 2389 KernelIDs.clear(); 2390 2391 return Assembly; 2392 } 2393 /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff` 2394 /// @param PwAffs The list of piecewise affine functions to create an 2395 /// `isl_pw_aff_list` from. We expect an rvalue ref because 2396 /// all the isl_pw_aff are used up by this function. 2397 /// 2398 /// @returns The `isl_pw_aff_list`. 2399 __isl_give isl_pw_aff_list * 2400 createPwAffList(isl_ctx *Context, 2401 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) { 2402 isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size()); 2403 2404 for (unsigned i = 0; i < PwAffs.size(); i++) { 2405 List = isl_pw_aff_list_insert(List, i, PwAffs[i]); 2406 } 2407 return List; 2408 } 2409 2410 /// Align all the `PwAffs` such that they have the same parameter dimensions. 2411 /// 2412 /// We loop over all `pw_aff` and align all of their spaces together to 2413 /// create a common space for all the `pw_aff`. This common space is the 2414 /// `AlignSpace`. We then align all the `pw_aff` to this space. We start 2415 /// with the given `SeedSpace`. 2416 /// @param PwAffs The list of piecewise affine functions we want to align. 2417 /// This is an rvalue reference because the entire vector is 2418 /// used up by the end of the operation. 2419 /// @param SeedSpace The space to start the alignment process with. 2420 /// @returns A std::pair, whose first element is the aligned space, 2421 /// whose second element is the vector of aligned piecewise 2422 /// affines. 2423 static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>> 2424 alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs, 2425 __isl_take isl_space *SeedSpace) { 2426 assert(SeedSpace && "Invalid seed space given."); 2427 2428 isl_space *AlignSpace = SeedSpace; 2429 for (isl_pw_aff *PwAff : PwAffs) { 2430 isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff); 2431 AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace); 2432 } 2433 std::vector<isl_pw_aff *> AdjustedPwAffs; 2434 2435 for (unsigned i = 0; i < PwAffs.size(); i++) { 2436 isl_pw_aff *Adjusted = PwAffs[i]; 2437 assert(Adjusted && "Invalid pw_aff given."); 2438 Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace)); 2439 AdjustedPwAffs.push_back(Adjusted); 2440 } 2441 return std::make_pair(AlignSpace, AdjustedPwAffs); 2442 } 2443 2444 namespace { 2445 class PPCGCodeGeneration : public ScopPass { 2446 public: 2447 static char ID; 2448 2449 GPURuntime Runtime = GPURuntime::CUDA; 2450 2451 GPUArch Architecture = GPUArch::NVPTX64; 2452 2453 /// The scop that is currently processed. 2454 Scop *S; 2455 2456 LoopInfo *LI; 2457 DominatorTree *DT; 2458 ScalarEvolution *SE; 2459 const DataLayout *DL; 2460 RegionInfo *RI; 2461 2462 PPCGCodeGeneration() : ScopPass(ID) {} 2463 2464 /// Construct compilation options for PPCG. 2465 /// 2466 /// @returns The compilation options. 2467 ppcg_options *createPPCGOptions() { 2468 auto DebugOptions = 2469 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2470 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2471 2472 DebugOptions->dump_schedule_constraints = false; 2473 DebugOptions->dump_schedule = false; 2474 DebugOptions->dump_final_schedule = false; 2475 DebugOptions->dump_sizes = false; 2476 DebugOptions->verbose = false; 2477 2478 Options->debug = DebugOptions; 2479 2480 Options->group_chains = false; 2481 Options->reschedule = true; 2482 Options->scale_tile_loops = false; 2483 Options->wrap = false; 2484 2485 Options->non_negative_parameters = false; 2486 Options->ctx = nullptr; 2487 Options->sizes = nullptr; 2488 2489 Options->tile = true; 2490 Options->tile_size = 32; 2491 2492 Options->isolate_full_tiles = false; 2493 2494 Options->use_private_memory = PrivateMemory; 2495 Options->use_shared_memory = SharedMemory; 2496 Options->max_shared_memory = 48 * 1024; 2497 2498 Options->target = PPCG_TARGET_CUDA; 2499 Options->openmp = false; 2500 Options->linearize_device_arrays = true; 2501 Options->allow_gnu_extensions = false; 2502 2503 Options->unroll_copy_shared = false; 2504 Options->unroll_gpu_tile = false; 2505 Options->live_range_reordering = true; 2506 2507 Options->live_range_reordering = true; 2508 Options->hybrid = false; 2509 Options->opencl_compiler_options = nullptr; 2510 Options->opencl_use_gpu = false; 2511 Options->opencl_n_include_file = 0; 2512 Options->opencl_include_files = nullptr; 2513 Options->opencl_print_kernel_types = false; 2514 Options->opencl_embed_kernel_code = false; 2515 2516 Options->save_schedule_file = nullptr; 2517 Options->load_schedule_file = nullptr; 2518 2519 return Options; 2520 } 2521 2522 /// Get a tagged access relation containing all accesses of type @p AccessTy. 2523 /// 2524 /// Instead of a normal access of the form: 2525 /// 2526 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2527 /// 2528 /// a tagged access has the form 2529 /// 2530 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2531 /// 2532 /// where 'id' is an additional space that references the memory access that 2533 /// triggered the access. 2534 /// 2535 /// @param AccessTy The type of the memory accesses to collect. 2536 /// 2537 /// @return The relation describing all tagged memory accesses. 2538 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2539 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2540 2541 for (auto &Stmt : *S) 2542 for (auto &Acc : Stmt) 2543 if (Acc->getType() == AccessTy) { 2544 isl_map *Relation = Acc->getAccessRelation().release(); 2545 Relation = 2546 isl_map_intersect_domain(Relation, Stmt.getDomain().release()); 2547 2548 isl_space *Space = isl_map_get_space(Relation); 2549 Space = isl_space_range(Space); 2550 Space = isl_space_from_range(Space); 2551 Space = 2552 isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2553 isl_map *Universe = isl_map_universe(Space); 2554 Relation = isl_map_domain_product(Relation, Universe); 2555 Accesses = isl_union_map_add_map(Accesses, Relation); 2556 } 2557 2558 return Accesses; 2559 } 2560 2561 /// Get the set of all read accesses, tagged with the access id. 2562 /// 2563 /// @see getTaggedAccesses 2564 isl_union_map *getTaggedReads() { 2565 return getTaggedAccesses(MemoryAccess::READ); 2566 } 2567 2568 /// Get the set of all may (and must) accesses, tagged with the access id. 2569 /// 2570 /// @see getTaggedAccesses 2571 isl_union_map *getTaggedMayWrites() { 2572 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2573 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2574 } 2575 2576 /// Get the set of all must accesses, tagged with the access id. 2577 /// 2578 /// @see getTaggedAccesses 2579 isl_union_map *getTaggedMustWrites() { 2580 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2581 } 2582 2583 /// Collect parameter and array names as isl_ids. 2584 /// 2585 /// To reason about the different parameters and arrays used, ppcg requires 2586 /// a list of all isl_ids in use. As PPCG traditionally performs 2587 /// source-to-source compilation each of these isl_ids is mapped to the 2588 /// expression that represents it. As we do not have a corresponding 2589 /// expression in Polly, we just map each id to a 'zero' expression to match 2590 /// the data format that ppcg expects. 2591 /// 2592 /// @returns Retun a map from collected ids to 'zero' ast expressions. 2593 __isl_give isl_id_to_ast_expr *getNames() { 2594 auto *Names = isl_id_to_ast_expr_alloc( 2595 S->getIslCtx(), 2596 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2597 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2598 2599 for (const SCEV *P : S->parameters()) { 2600 isl_id *Id = S->getIdForParam(P); 2601 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2602 } 2603 2604 for (auto &Array : S->arrays()) { 2605 auto Id = Array->getBasePtrId().release(); 2606 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2607 } 2608 2609 isl_ast_expr_free(Zero); 2610 2611 return Names; 2612 } 2613 2614 /// Create a new PPCG scop from the current scop. 2615 /// 2616 /// The PPCG scop is initialized with data from the current polly::Scop. From 2617 /// this initial data, the data-dependences in the PPCG scop are initialized. 2618 /// We do not use Polly's dependence analysis for now, to ensure we match 2619 /// the PPCG default behaviour more closely. 2620 /// 2621 /// @returns A new ppcg scop. 2622 ppcg_scop *createPPCGScop() { 2623 MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2624 2625 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2626 2627 PPCGScop->options = createPPCGOptions(); 2628 // enable live range reordering 2629 PPCGScop->options->live_range_reordering = 1; 2630 2631 PPCGScop->start = 0; 2632 PPCGScop->end = 0; 2633 2634 PPCGScop->context = S->getContext(); 2635 PPCGScop->domain = S->getDomains(); 2636 // TODO: investigate this further. PPCG calls collect_call_domains. 2637 PPCGScop->call = isl_union_set_from_set(S->getContext()); 2638 PPCGScop->tagged_reads = getTaggedReads(); 2639 PPCGScop->reads = S->getReads().release(); 2640 PPCGScop->live_in = nullptr; 2641 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2642 PPCGScop->may_writes = S->getWrites().release(); 2643 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2644 PPCGScop->must_writes = S->getMustWrites().release(); 2645 PPCGScop->live_out = nullptr; 2646 PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2647 PPCGScop->must_kills = KillsInfo.MustKills.take(); 2648 2649 PPCGScop->tagger = nullptr; 2650 PPCGScop->independence = 2651 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2652 PPCGScop->dep_flow = nullptr; 2653 PPCGScop->tagged_dep_flow = nullptr; 2654 PPCGScop->dep_false = nullptr; 2655 PPCGScop->dep_forced = nullptr; 2656 PPCGScop->dep_order = nullptr; 2657 PPCGScop->tagged_dep_order = nullptr; 2658 2659 PPCGScop->schedule = S->getScheduleTree(); 2660 // If we have something non-trivial to kill, add it to the schedule 2661 if (KillsInfo.KillsSchedule.get()) 2662 PPCGScop->schedule = isl_schedule_sequence( 2663 PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2664 2665 PPCGScop->names = getNames(); 2666 PPCGScop->pet = nullptr; 2667 2668 compute_tagger(PPCGScop); 2669 compute_dependences(PPCGScop); 2670 eliminate_dead_code(PPCGScop); 2671 2672 return PPCGScop; 2673 } 2674 2675 /// Collect the array accesses in a statement. 2676 /// 2677 /// @param Stmt The statement for which to collect the accesses. 2678 /// 2679 /// @returns A list of array accesses. 2680 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 2681 gpu_stmt_access *Accesses = nullptr; 2682 2683 for (MemoryAccess *Acc : Stmt) { 2684 auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 2685 Access->read = Acc->isRead(); 2686 Access->write = Acc->isWrite(); 2687 Access->access = Acc->getAccessRelation().release(); 2688 isl_space *Space = isl_map_get_space(Access->access); 2689 Space = isl_space_range(Space); 2690 Space = isl_space_from_range(Space); 2691 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release()); 2692 isl_map *Universe = isl_map_universe(Space); 2693 Access->tagged_access = 2694 isl_map_domain_product(Acc->getAccessRelation().release(), Universe); 2695 Access->exact_write = !Acc->isMayWrite(); 2696 Access->ref_id = Acc->getId().release(); 2697 Access->next = Accesses; 2698 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2699 Accesses = Access; 2700 } 2701 2702 return Accesses; 2703 } 2704 2705 /// Collect the list of GPU statements. 2706 /// 2707 /// Each statement has an id, a pointer to the underlying data structure, 2708 /// as well as a list with all memory accesses. 2709 /// 2710 /// TODO: Initialize the list of memory accesses. 2711 /// 2712 /// @returns A linked-list of statements. 2713 gpu_stmt *getStatements() { 2714 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 2715 std::distance(S->begin(), S->end())); 2716 2717 int i = 0; 2718 for (auto &Stmt : *S) { 2719 gpu_stmt *GPUStmt = &Stmts[i]; 2720 2721 GPUStmt->id = Stmt.getDomainId().release(); 2722 2723 // We use the pet stmt pointer to keep track of the Polly statements. 2724 GPUStmt->stmt = (pet_stmt *)&Stmt; 2725 GPUStmt->accesses = getStmtAccesses(Stmt); 2726 i++; 2727 } 2728 2729 return Stmts; 2730 } 2731 2732 /// Derive the extent of an array. 2733 /// 2734 /// The extent of an array is the set of elements that are within the 2735 /// accessed array. For the inner dimensions, the extent constraints are 2736 /// 0 and the size of the corresponding array dimension. For the first 2737 /// (outermost) dimension, the extent constraints are the minimal and maximal 2738 /// subscript value for the first dimension. 2739 /// 2740 /// @param Array The array to derive the extent for. 2741 /// 2742 /// @returns An isl_set describing the extent of the array. 2743 __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2744 unsigned NumDims = Array->getNumberOfDimensions(); 2745 isl_union_map *Accesses = S->getAccesses().release(); 2746 Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2747 Accesses = isl_union_map_detect_equalities(Accesses); 2748 isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2749 AccessUSet = isl_union_set_coalesce(AccessUSet); 2750 AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2751 AccessUSet = isl_union_set_coalesce(AccessUSet); 2752 2753 if (isl_union_set_is_empty(AccessUSet)) { 2754 isl_union_set_free(AccessUSet); 2755 return isl_set_empty(Array->getSpace().release()); 2756 } 2757 2758 if (Array->getNumberOfDimensions() == 0) { 2759 isl_union_set_free(AccessUSet); 2760 return isl_set_universe(Array->getSpace().release()); 2761 } 2762 2763 isl_set *AccessSet = 2764 isl_union_set_extract_set(AccessUSet, Array->getSpace().release()); 2765 2766 isl_union_set_free(AccessUSet); 2767 isl_local_space *LS = 2768 isl_local_space_from_space(Array->getSpace().release()); 2769 2770 isl_pw_aff *Val = 2771 isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2772 2773 isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2774 isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2775 OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2776 isl_pw_aff_dim(Val, isl_dim_in)); 2777 OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2778 isl_pw_aff_dim(Val, isl_dim_in)); 2779 OuterMin = isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, 2780 Array->getBasePtrId().release()); 2781 OuterMax = isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, 2782 Array->getBasePtrId().release()); 2783 2784 isl_set *Extent = isl_set_universe(Array->getSpace().release()); 2785 2786 Extent = isl_set_intersect( 2787 Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2788 Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2789 2790 for (unsigned i = 1; i < NumDims; ++i) 2791 Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2792 2793 for (unsigned i = 0; i < NumDims; ++i) { 2794 isl_pw_aff *PwAff = 2795 const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i).release()); 2796 2797 // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2798 // Fortran array will we have a legitimate dimension. 2799 if (!PwAff) { 2800 assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2801 continue; 2802 } 2803 2804 isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2805 isl_local_space_from_space(Array->getSpace().release()), isl_dim_set, 2806 i)); 2807 PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2808 isl_pw_aff_dim(Val, isl_dim_in)); 2809 PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2810 isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2811 auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2812 Extent = isl_set_intersect(Set, Extent); 2813 } 2814 2815 return Extent; 2816 } 2817 2818 /// Derive the bounds of an array. 2819 /// 2820 /// For the first dimension we derive the bound of the array from the extent 2821 /// of this dimension. For inner dimensions we obtain their size directly from 2822 /// ScopArrayInfo. 2823 /// 2824 /// @param PPCGArray The array to compute bounds for. 2825 /// @param Array The polly array from which to take the information. 2826 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2827 std::vector<isl_pw_aff *> Bounds; 2828 2829 if (PPCGArray.n_index > 0) { 2830 if (isl_set_is_empty(PPCGArray.extent)) { 2831 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2832 isl_local_space *LS = isl_local_space_from_space( 2833 isl_space_params(isl_set_get_space(Dom))); 2834 isl_set_free(Dom); 2835 isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2836 Bounds.push_back(Zero); 2837 } else { 2838 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2839 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 2840 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 2841 isl_set_free(Dom); 2842 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 2843 isl_local_space *LS = 2844 isl_local_space_from_space(isl_set_get_space(Dom)); 2845 isl_aff *One = isl_aff_zero_on_domain(LS); 2846 One = isl_aff_add_constant_si(One, 1); 2847 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 2848 Bound = isl_pw_aff_gist(Bound, S->getContext()); 2849 Bounds.push_back(Bound); 2850 } 2851 } 2852 2853 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2854 isl_pw_aff *Bound = Array->getDimensionSizePw(i).release(); 2855 auto LS = isl_pw_aff_get_domain_space(Bound); 2856 auto Aff = isl_multi_aff_zero(LS); 2857 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2858 Bounds.push_back(Bound); 2859 } 2860 2861 /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff` 2862 /// to have the same parameter dimensions. So, we need to align them to an 2863 /// appropriate space. 2864 /// Scop::Context is _not_ an appropriate space, because when we have 2865 /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not 2866 /// contain all parameter dimensions. 2867 /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together. 2868 isl_space *SeedAlignSpace = S->getParamSpace(); 2869 SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1); 2870 2871 isl_space *AlignSpace = nullptr; 2872 std::vector<isl_pw_aff *> AlignedBounds; 2873 std::tie(AlignSpace, AlignedBounds) = 2874 alignPwAffs(std::move(Bounds), SeedAlignSpace); 2875 2876 assert(AlignSpace && "alignPwAffs did not initialise AlignSpace"); 2877 2878 isl_pw_aff_list *BoundsList = 2879 createPwAffList(S->getIslCtx(), std::move(AlignedBounds)); 2880 2881 isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2882 BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace); 2883 2884 assert(BoundsSpace && "Unable to access space of array."); 2885 assert(BoundsList && "Unable to access list of bounds."); 2886 2887 PPCGArray.bound = 2888 isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 2889 assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 2890 } 2891 2892 /// Create the arrays for @p PPCGProg. 2893 /// 2894 /// @param PPCGProg The program to compute the arrays for. 2895 void createArrays(gpu_prog *PPCGProg, 2896 const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) { 2897 int i = 0; 2898 for (auto &Array : ValidSAIs) { 2899 std::string TypeName; 2900 raw_string_ostream OS(TypeName); 2901 2902 OS << *Array->getElementType(); 2903 TypeName = OS.str(); 2904 2905 gpu_array_info &PPCGArray = PPCGProg->array[i]; 2906 2907 PPCGArray.space = Array->getSpace().release(); 2908 PPCGArray.type = strdup(TypeName.c_str()); 2909 PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 2910 PPCGArray.name = strdup(Array->getName().c_str()); 2911 PPCGArray.extent = nullptr; 2912 PPCGArray.n_index = Array->getNumberOfDimensions(); 2913 PPCGArray.extent = getExtent(Array); 2914 PPCGArray.n_ref = 0; 2915 PPCGArray.refs = nullptr; 2916 PPCGArray.accessed = true; 2917 PPCGArray.read_only_scalar = 2918 Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 2919 PPCGArray.has_compound_element = false; 2920 PPCGArray.local = false; 2921 PPCGArray.declare_local = false; 2922 PPCGArray.global = false; 2923 PPCGArray.linearize = false; 2924 PPCGArray.dep_order = nullptr; 2925 PPCGArray.user = Array; 2926 2927 PPCGArray.bound = nullptr; 2928 setArrayBounds(PPCGArray, Array); 2929 i++; 2930 2931 collect_references(PPCGProg, &PPCGArray); 2932 } 2933 } 2934 2935 /// Create an identity map between the arrays in the scop. 2936 /// 2937 /// @returns An identity map between the arrays in the scop. 2938 isl_union_map *getArrayIdentity() { 2939 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 2940 2941 for (auto &Array : S->arrays()) { 2942 isl_space *Space = Array->getSpace().release(); 2943 Space = isl_space_map_from_set(Space); 2944 isl_map *Identity = isl_map_identity(Space); 2945 Maps = isl_union_map_add_map(Maps, Identity); 2946 } 2947 2948 return Maps; 2949 } 2950 2951 /// Create a default-initialized PPCG GPU program. 2952 /// 2953 /// @returns A new gpu program description. 2954 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2955 2956 if (!PPCGScop) 2957 return nullptr; 2958 2959 auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2960 2961 PPCGProg->ctx = S->getIslCtx(); 2962 PPCGProg->scop = PPCGScop; 2963 PPCGProg->context = isl_set_copy(PPCGScop->context); 2964 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 2965 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 2966 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 2967 PPCGProg->tagged_must_kill = 2968 isl_union_map_copy(PPCGScop->tagged_must_kills); 2969 PPCGProg->to_inner = getArrayIdentity(); 2970 PPCGProg->to_outer = getArrayIdentity(); 2971 // TODO: verify that this assignment is correct. 2972 PPCGProg->any_to_outer = nullptr; 2973 2974 // this needs to be set when live range reordering is enabled. 2975 // NOTE: I believe that is conservatively correct. I'm not sure 2976 // what the semantics of this is. 2977 // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2978 PPCGProg->array_order = 2979 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2980 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 2981 PPCGProg->stmts = getStatements(); 2982 2983 // Only consider arrays that have a non-empty extent. 2984 // Otherwise, this will cause us to consider the following kinds of 2985 // empty arrays: 2986 // 1. Invariant loads that are represented by SAI objects. 2987 // 2. Arrays with statically known zero size. 2988 auto ValidSAIsRange = 2989 make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool { 2990 return !isl::manage(getExtent(SAI)).is_empty(); 2991 }); 2992 SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(), 2993 ValidSAIsRange.end()); 2994 2995 PPCGProg->n_array = 2996 ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end()); 2997 PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 2998 PPCGProg->n_array); 2999 3000 createArrays(PPCGProg, ValidSAIs); 3001 3002 PPCGProg->may_persist = compute_may_persist(PPCGProg); 3003 return PPCGProg; 3004 } 3005 3006 struct PrintGPUUserData { 3007 struct cuda_info *CudaInfo; 3008 struct gpu_prog *PPCGProg; 3009 std::vector<ppcg_kernel *> Kernels; 3010 }; 3011 3012 /// Print a user statement node in the host code. 3013 /// 3014 /// We use ppcg's printing facilities to print the actual statement and 3015 /// additionally build up a list of all kernels that are encountered in the 3016 /// host ast. 3017 /// 3018 /// @param P The printer to print to 3019 /// @param Options The printing options to use 3020 /// @param Node The node to print 3021 /// @param User A user pointer to carry additional data. This pointer is 3022 /// expected to be of type PrintGPUUserData. 3023 /// 3024 /// @returns A printer to which the output has been printed. 3025 static __isl_give isl_printer * 3026 printHostUser(__isl_take isl_printer *P, 3027 __isl_take isl_ast_print_options *Options, 3028 __isl_take isl_ast_node *Node, void *User) { 3029 auto Data = (struct PrintGPUUserData *)User; 3030 auto Id = isl_ast_node_get_annotation(Node); 3031 3032 if (Id) { 3033 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 3034 3035 // If this is a user statement, format it ourselves as ppcg would 3036 // otherwise try to call pet functionality that is not available in 3037 // Polly. 3038 if (IsUser) { 3039 P = isl_printer_start_line(P); 3040 P = isl_printer_print_ast_node(P, Node); 3041 P = isl_printer_end_line(P); 3042 isl_id_free(Id); 3043 isl_ast_print_options_free(Options); 3044 return P; 3045 } 3046 3047 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 3048 isl_id_free(Id); 3049 Data->Kernels.push_back(Kernel); 3050 } 3051 3052 return print_host_user(P, Options, Node, User); 3053 } 3054 3055 /// Print C code corresponding to the control flow in @p Kernel. 3056 /// 3057 /// @param Kernel The kernel to print 3058 void printKernel(ppcg_kernel *Kernel) { 3059 auto *P = isl_printer_to_str(S->getIslCtx()); 3060 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 3061 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 3062 P = isl_ast_node_print(Kernel->tree, P, Options); 3063 char *String = isl_printer_get_str(P); 3064 printf("%s\n", String); 3065 free(String); 3066 isl_printer_free(P); 3067 } 3068 3069 /// Print C code corresponding to the GPU code described by @p Tree. 3070 /// 3071 /// @param Tree An AST describing GPU code 3072 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 3073 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 3074 auto *P = isl_printer_to_str(S->getIslCtx()); 3075 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 3076 3077 PrintGPUUserData Data; 3078 Data.PPCGProg = PPCGProg; 3079 3080 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 3081 Options = 3082 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 3083 P = isl_ast_node_print(Tree, P, Options); 3084 char *String = isl_printer_get_str(P); 3085 printf("# host\n"); 3086 printf("%s\n", String); 3087 free(String); 3088 isl_printer_free(P); 3089 3090 for (auto Kernel : Data.Kernels) { 3091 printf("# kernel%d\n", Kernel->id); 3092 printKernel(Kernel); 3093 } 3094 } 3095 3096 // Generate a GPU program using PPCG. 3097 // 3098 // GPU mapping consists of multiple steps: 3099 // 3100 // 1) Compute new schedule for the program. 3101 // 2) Map schedule to GPU (TODO) 3102 // 3) Generate code for new schedule (TODO) 3103 // 3104 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 3105 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 3106 // strategy directly from this pass. 3107 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 3108 3109 auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 3110 3111 PPCGGen->ctx = S->getIslCtx(); 3112 PPCGGen->options = PPCGScop->options; 3113 PPCGGen->print = nullptr; 3114 PPCGGen->print_user = nullptr; 3115 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 3116 PPCGGen->prog = PPCGProg; 3117 PPCGGen->tree = nullptr; 3118 PPCGGen->types.n = 0; 3119 PPCGGen->types.name = nullptr; 3120 PPCGGen->sizes = nullptr; 3121 PPCGGen->used_sizes = nullptr; 3122 PPCGGen->kernel_id = 0; 3123 3124 // Set scheduling strategy to same strategy PPCG is using. 3125 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 3126 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 3127 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 3128 3129 isl_schedule *Schedule = get_schedule(PPCGGen); 3130 3131 int has_permutable = has_any_permutable_node(Schedule); 3132 3133 Schedule = 3134 isl_schedule_align_params(Schedule, S->getFullParamSpace().release()); 3135 3136 if (!has_permutable || has_permutable < 0) { 3137 Schedule = isl_schedule_free(Schedule); 3138 DEBUG(dbgs() << getUniqueScopName(S) 3139 << " does not have permutable bands. Bailing out\n";); 3140 } else { 3141 Schedule = map_to_device(PPCGGen, Schedule); 3142 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 3143 } 3144 3145 if (DumpSchedule) { 3146 isl_printer *P = isl_printer_to_str(S->getIslCtx()); 3147 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 3148 P = isl_printer_print_str(P, "Schedule\n"); 3149 P = isl_printer_print_str(P, "========\n"); 3150 if (Schedule) 3151 P = isl_printer_print_schedule(P, Schedule); 3152 else 3153 P = isl_printer_print_str(P, "No schedule found\n"); 3154 3155 printf("%s\n", isl_printer_get_str(P)); 3156 isl_printer_free(P); 3157 } 3158 3159 if (DumpCode) { 3160 printf("Code\n"); 3161 printf("====\n"); 3162 if (PPCGGen->tree) 3163 printGPUTree(PPCGGen->tree, PPCGProg); 3164 else 3165 printf("No code generated\n"); 3166 } 3167 3168 isl_schedule_free(Schedule); 3169 3170 return PPCGGen; 3171 } 3172 3173 /// Free gpu_gen structure. 3174 /// 3175 /// @param PPCGGen The ppcg_gen object to free. 3176 void freePPCGGen(gpu_gen *PPCGGen) { 3177 isl_ast_node_free(PPCGGen->tree); 3178 isl_union_map_free(PPCGGen->sizes); 3179 isl_union_map_free(PPCGGen->used_sizes); 3180 free(PPCGGen); 3181 } 3182 3183 /// Free the options in the ppcg scop structure. 3184 /// 3185 /// ppcg is not freeing these options for us. To avoid leaks we do this 3186 /// ourselves. 3187 /// 3188 /// @param PPCGScop The scop referencing the options to free. 3189 void freeOptions(ppcg_scop *PPCGScop) { 3190 free(PPCGScop->options->debug); 3191 PPCGScop->options->debug = nullptr; 3192 free(PPCGScop->options); 3193 PPCGScop->options = nullptr; 3194 } 3195 3196 /// Approximate the number of points in the set. 3197 /// 3198 /// This function returns an ast expression that overapproximates the number 3199 /// of points in an isl set through the rectangular hull surrounding this set. 3200 /// 3201 /// @param Set The set to count. 3202 /// @param Build The isl ast build object to use for creating the ast 3203 /// expression. 3204 /// 3205 /// @returns An approximation of the number of points in the set. 3206 __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 3207 __isl_keep isl_ast_build *Build) { 3208 3209 isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 3210 auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 3211 3212 isl_space *Space = isl_set_get_space(Set); 3213 Space = isl_space_params(Space); 3214 auto *Univ = isl_set_universe(Space); 3215 isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 3216 3217 for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 3218 isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 3219 isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 3220 isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 3221 DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 3222 auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 3223 Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 3224 } 3225 3226 isl_set_free(Set); 3227 isl_pw_aff_free(OneAff); 3228 3229 return Expr; 3230 } 3231 3232 /// Approximate a number of dynamic instructions executed by a given 3233 /// statement. 3234 /// 3235 /// @param Stmt The statement for which to compute the number of dynamic 3236 /// instructions. 3237 /// @param Build The isl ast build object to use for creating the ast 3238 /// expression. 3239 /// @returns An approximation of the number of dynamic instructions executed 3240 /// by @p Stmt. 3241 __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 3242 __isl_keep isl_ast_build *Build) { 3243 auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build); 3244 3245 long InstCount = 0; 3246 3247 if (Stmt.isBlockStmt()) { 3248 auto *BB = Stmt.getBasicBlock(); 3249 InstCount = std::distance(BB->begin(), BB->end()); 3250 } else { 3251 auto *R = Stmt.getRegion(); 3252 3253 for (auto *BB : R->blocks()) { 3254 InstCount += std::distance(BB->begin(), BB->end()); 3255 } 3256 } 3257 3258 isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 3259 auto *InstExpr = isl_ast_expr_from_val(InstVal); 3260 return isl_ast_expr_mul(InstExpr, Iterations); 3261 } 3262 3263 /// Approximate dynamic instructions executed in scop. 3264 /// 3265 /// @param S The scop for which to approximate dynamic instructions. 3266 /// @param Build The isl ast build object to use for creating the ast 3267 /// expression. 3268 /// @returns An approximation of the number of dynamic instructions executed 3269 /// in @p S. 3270 __isl_give isl_ast_expr * 3271 getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 3272 isl_ast_expr *Instructions; 3273 3274 isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 3275 Instructions = isl_ast_expr_from_val(Zero); 3276 3277 for (ScopStmt &Stmt : S) { 3278 isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 3279 Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 3280 } 3281 return Instructions; 3282 } 3283 3284 /// Create a check that ensures sufficient compute in scop. 3285 /// 3286 /// @param S The scop for which to ensure sufficient compute. 3287 /// @param Build The isl ast build object to use for creating the ast 3288 /// expression. 3289 /// @returns An expression that evaluates to TRUE in case of sufficient 3290 /// compute and to FALSE, otherwise. 3291 __isl_give isl_ast_expr * 3292 createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 3293 auto Iterations = getNumberOfIterations(S, Build); 3294 auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 3295 auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 3296 return isl_ast_expr_ge(Iterations, MinComputeExpr); 3297 } 3298 3299 /// Check if the basic block contains a function we cannot codegen for GPU 3300 /// kernels. 3301 /// 3302 /// If this basic block does something with a `Function` other than calling 3303 /// a function that we support in a kernel, return true. 3304 bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB, 3305 bool AllowCUDALibDevice) { 3306 for (const Instruction &Inst : *BB) { 3307 const CallInst *Call = dyn_cast<CallInst>(&Inst); 3308 if (Call && isValidFunctionInKernel(Call->getCalledFunction(), 3309 AllowCUDALibDevice)) { 3310 continue; 3311 } 3312 3313 for (Value *SrcVal : Inst.operands()) { 3314 PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 3315 if (!p) 3316 continue; 3317 if (isa<FunctionType>(p->getElementType())) 3318 return true; 3319 } 3320 } 3321 return false; 3322 } 3323 3324 /// Return whether the Scop S uses functions in a way that we do not support. 3325 bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) { 3326 for (auto &Stmt : S) { 3327 if (Stmt.isBlockStmt()) { 3328 if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(), 3329 AllowCUDALibDevice)) 3330 return true; 3331 } else { 3332 assert(Stmt.isRegionStmt() && 3333 "Stmt was neither block nor region statement"); 3334 for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 3335 if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice)) 3336 return true; 3337 } 3338 } 3339 return false; 3340 } 3341 3342 /// Generate code for a given GPU AST described by @p Root. 3343 /// 3344 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 3345 /// @param Prog The GPU Program to generate code for. 3346 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 3347 ScopAnnotator Annotator; 3348 Annotator.buildAliasScopes(*S); 3349 3350 Region *R = &S->getRegion(); 3351 3352 simplifyRegion(R, DT, LI, RI); 3353 3354 BasicBlock *EnteringBB = R->getEnteringBlock(); 3355 3356 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 3357 3358 // Only build the run-time condition and parameters _after_ having 3359 // introduced the conditional branch. This is important as the conditional 3360 // branch will guard the original scop from new induction variables that 3361 // the SCEVExpander may introduce while code generating the parameters and 3362 // which may introduce scalar dependences that prevent us from correctly 3363 // code generating this scop. 3364 BBPair StartExitBlocks; 3365 BranchInst *CondBr = nullptr; 3366 std::tie(StartExitBlocks, CondBr) = 3367 executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3368 BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 3369 3370 assert(CondBr && "CondBr not initialized by executeScopConditionally"); 3371 3372 GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 3373 StartBlock, Prog, Runtime, Architecture); 3374 3375 // TODO: Handle LICM 3376 auto SplitBlock = StartBlock->getSinglePredecessor(); 3377 Builder.SetInsertPoint(SplitBlock->getTerminator()); 3378 NodeBuilder.addParameters(S->getContext()); 3379 3380 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 3381 isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 3382 isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 3383 Condition = isl_ast_expr_and(Condition, SufficientCompute); 3384 isl_ast_build_free(Build); 3385 3386 // preload invariant loads. Note: This should happen before the RTC 3387 // because the RTC may depend on values that are invariant load hoisted. 3388 if (!NodeBuilder.preloadInvariantLoads()) 3389 report_fatal_error("preloading invariant loads failed in function: " + 3390 S->getFunction().getName() + 3391 " | Scop Region: " + S->getNameStr()); 3392 3393 Value *RTC = NodeBuilder.createRTC(Condition); 3394 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3395 3396 Builder.SetInsertPoint(&*StartBlock->begin()); 3397 3398 NodeBuilder.create(Root); 3399 3400 /// In case a sequential kernel has more surrounding loops as any parallel 3401 /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3402 /// point in running it on a GPU. 3403 if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 3404 CondBr->setOperand(0, Builder.getFalse()); 3405 3406 if (!NodeBuilder.BuildSuccessful) 3407 CondBr->setOperand(0, Builder.getFalse()); 3408 } 3409 3410 bool runOnScop(Scop &CurrentScop) override { 3411 S = &CurrentScop; 3412 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3413 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3414 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 3415 DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 3416 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3417 3418 // We currently do not support functions other than intrinsics inside 3419 // kernels, as code generation will need to offload function calls to the 3420 // kernel. This may lead to a kernel trying to call a function on the host. 3421 // This also allows us to prevent codegen from trying to take the 3422 // address of an intrinsic function to send to the kernel. 3423 if (containsInvalidKernelFunction(CurrentScop, 3424 Architecture == GPUArch::NVPTX64)) { 3425 DEBUG( 3426 dbgs() << getUniqueScopName(S) 3427 << " contains function which cannot be materialised in a GPU " 3428 "kernel. Bailing out.\n";); 3429 return false; 3430 } 3431 3432 auto PPCGScop = createPPCGScop(); 3433 auto PPCGProg = createPPCGProg(PPCGScop); 3434 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 3435 3436 if (PPCGGen->tree) { 3437 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 3438 CurrentScop.markAsToBeSkipped(); 3439 } else { 3440 DEBUG(dbgs() << getUniqueScopName(S) 3441 << " has empty PPCGGen->tree. Bailing out.\n"); 3442 } 3443 3444 freeOptions(PPCGScop); 3445 freePPCGGen(PPCGGen); 3446 gpu_prog_free(PPCGProg); 3447 ppcg_scop_free(PPCGScop); 3448 3449 return true; 3450 } 3451 3452 void printScop(raw_ostream &, Scop &) const override {} 3453 3454 void getAnalysisUsage(AnalysisUsage &AU) const override { 3455 AU.addRequired<DominatorTreeWrapperPass>(); 3456 AU.addRequired<RegionInfoPass>(); 3457 AU.addRequired<ScalarEvolutionWrapperPass>(); 3458 AU.addRequired<ScopDetectionWrapperPass>(); 3459 AU.addRequired<ScopInfoRegionPass>(); 3460 AU.addRequired<LoopInfoWrapperPass>(); 3461 3462 AU.addPreserved<AAResultsWrapperPass>(); 3463 AU.addPreserved<BasicAAWrapperPass>(); 3464 AU.addPreserved<LoopInfoWrapperPass>(); 3465 AU.addPreserved<DominatorTreeWrapperPass>(); 3466 AU.addPreserved<GlobalsAAWrapperPass>(); 3467 AU.addPreserved<ScopDetectionWrapperPass>(); 3468 AU.addPreserved<ScalarEvolutionWrapperPass>(); 3469 AU.addPreserved<SCEVAAWrapperPass>(); 3470 3471 // FIXME: We do not yet add regions for the newly generated code to the 3472 // region tree. 3473 AU.addPreserved<RegionInfoPass>(); 3474 AU.addPreserved<ScopInfoRegionPass>(); 3475 } 3476 }; 3477 } // namespace 3478 3479 char PPCGCodeGeneration::ID = 1; 3480 3481 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 3482 PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 3483 generator->Runtime = Runtime; 3484 generator->Architecture = Arch; 3485 return generator; 3486 } 3487 3488 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 3489 "Polly - Apply PPCG translation to SCOP", false, false) 3490 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 3491 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 3492 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 3493 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 3494 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 3495 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 3496 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 3497 "Polly - Apply PPCG translation to SCOP", false, false) 3498