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