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/IslAst.h" 16 #include "polly/CodeGen/IslNodeBuilder.h" 17 #include "polly/CodeGen/Utils.h" 18 #include "polly/DependenceInfo.h" 19 #include "polly/LinkAllPasses.h" 20 #include "polly/Options.h" 21 #include "polly/ScopDetection.h" 22 #include "polly/ScopInfo.h" 23 #include "polly/Support/SCEVValidator.h" 24 #include "llvm/ADT/PostOrderIterator.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/BasicAliasAnalysis.h" 27 #include "llvm/Analysis/GlobalsModRef.h" 28 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/TargetTransformInfo.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Verifier.h" 33 #include "llvm/Support/TargetRegistry.h" 34 #include "llvm/Support/TargetSelect.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 39 #include "isl/union_map.h" 40 41 extern "C" { 42 #include "ppcg/cuda.h" 43 #include "ppcg/gpu.h" 44 #include "ppcg/gpu_print.h" 45 #include "ppcg/ppcg.h" 46 #include "ppcg/schedule.h" 47 } 48 49 #include "llvm/Support/Debug.h" 50 51 using namespace polly; 52 using namespace llvm; 53 54 #define DEBUG_TYPE "polly-codegen-ppcg" 55 56 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule", 57 cl::desc("Dump the computed GPU Schedule"), 58 cl::Hidden, cl::init(false), cl::ZeroOrMore, 59 cl::cat(PollyCategory)); 60 61 static cl::opt<bool> 62 DumpCode("polly-acc-dump-code", 63 cl::desc("Dump C code describing the GPU mapping"), cl::Hidden, 64 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 65 66 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir", 67 cl::desc("Dump the kernel LLVM-IR"), 68 cl::Hidden, cl::init(false), cl::ZeroOrMore, 69 cl::cat(PollyCategory)); 70 71 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm", 72 cl::desc("Dump the kernel assembly code"), 73 cl::Hidden, cl::init(false), cl::ZeroOrMore, 74 cl::cat(PollyCategory)); 75 76 static cl::opt<bool> FastMath("polly-acc-fastmath", 77 cl::desc("Allow unsafe math optimizations"), 78 cl::Hidden, cl::init(false), cl::ZeroOrMore, 79 cl::cat(PollyCategory)); 80 static cl::opt<bool> SharedMemory("polly-acc-use-shared", 81 cl::desc("Use shared memory"), cl::Hidden, 82 cl::init(false), cl::ZeroOrMore, 83 cl::cat(PollyCategory)); 84 static cl::opt<bool> PrivateMemory("polly-acc-use-private", 85 cl::desc("Use private memory"), cl::Hidden, 86 cl::init(false), cl::ZeroOrMore, 87 cl::cat(PollyCategory)); 88 89 static cl::opt<std::string> 90 CudaVersion("polly-acc-cuda-version", 91 cl::desc("The CUDA version to compile for"), cl::Hidden, 92 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 93 94 static cl::opt<int> 95 MinCompute("polly-acc-mincompute", 96 cl::desc("Minimal number of compute statements to run on GPU."), 97 cl::Hidden, cl::init(10 * 512 * 512)); 98 99 /// Create the ast expressions for a ScopStmt. 100 /// 101 /// This function is a callback for to generate the ast expressions for each 102 /// of the scheduled ScopStmts. 103 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 104 void *StmtT, isl_ast_build *Build, 105 isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 106 isl_id *Id, void *User), 107 void *UserIndex, 108 isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 109 void *UserExpr) { 110 111 ScopStmt *Stmt = (ScopStmt *)StmtT; 112 113 isl_ctx *Ctx; 114 115 if (!Stmt || !Build) 116 return NULL; 117 118 Ctx = isl_ast_build_get_ctx(Build); 119 isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 120 121 for (MemoryAccess *Acc : *Stmt) { 122 isl_map *AddrFunc = Acc->getAddressFunction(); 123 AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 124 isl_id *RefId = Acc->getId(); 125 isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 126 isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 127 MPA = isl_multi_pw_aff_coalesce(MPA); 128 MPA = FunctionIndex(MPA, RefId, UserIndex); 129 isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 130 Access = FunctionExpr(Access, RefId, UserExpr); 131 RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 132 } 133 134 return RefToExpr; 135 } 136 137 /// Generate code for a GPU specific isl AST. 138 /// 139 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 140 /// generates code for general-prupose AST nodes, with special functionality 141 /// for generating GPU specific user nodes. 142 /// 143 /// @see GPUNodeBuilder::createUser 144 class GPUNodeBuilder : public IslNodeBuilder { 145 public: 146 GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 147 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 148 DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 149 gpu_prog *Prog) 150 : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 151 Prog(Prog) { 152 getExprBuilder().setIDToSAI(&IDToSAI); 153 } 154 155 /// Create after-run-time-check initialization code. 156 void initializeAfterRTH(); 157 158 /// Finalize the generated scop. 159 virtual void finalize(); 160 161 /// Track if the full build process was successful. 162 /// 163 /// This value is set to false, if throughout the build process an error 164 /// occurred which prevents us from generating valid GPU code. 165 bool BuildSuccessful = true; 166 167 /// The maximal number of loops surrounding a sequential kernel. 168 unsigned DeepestSequential = 0; 169 170 /// The maximal number of loops surrounding a parallel kernel. 171 unsigned DeepestParallel = 0; 172 173 private: 174 /// A vector of array base pointers for which a new ScopArrayInfo was created. 175 /// 176 /// This vector is used to delete the ScopArrayInfo when it is not needed any 177 /// more. 178 std::vector<Value *> LocalArrays; 179 180 /// A map from ScopArrays to their corresponding device allocations. 181 std::map<ScopArrayInfo *, Value *> DeviceAllocations; 182 183 /// The current GPU context. 184 Value *GPUContext; 185 186 /// The set of isl_ids allocated in the kernel 187 std::vector<isl_id *> KernelIds; 188 189 /// A module containing GPU code. 190 /// 191 /// This pointer is only set in case we are currently generating GPU code. 192 std::unique_ptr<Module> GPUModule; 193 194 /// The GPU program we generate code for. 195 gpu_prog *Prog; 196 197 /// Class to free isl_ids. 198 class IslIdDeleter { 199 public: 200 void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 201 }; 202 203 /// A set containing all isl_ids allocated in a GPU kernel. 204 /// 205 /// By releasing this set all isl_ids will be freed. 206 std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 207 208 IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 209 210 /// Create code for user-defined AST nodes. 211 /// 212 /// These AST nodes can be of type: 213 /// 214 /// - ScopStmt: A computational statement (TODO) 215 /// - Kernel: A GPU kernel call (TODO) 216 /// - Data-Transfer: A GPU <-> CPU data-transfer 217 /// - In-kernel synchronization 218 /// - In-kernel memory copy statement 219 /// 220 /// @param UserStmt The ast node to generate code for. 221 virtual void createUser(__isl_take isl_ast_node *UserStmt); 222 223 enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 224 225 /// Create code for a data transfer statement 226 /// 227 /// @param TransferStmt The data transfer statement. 228 /// @param Direction The direction in which to transfer data. 229 void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 230 enum DataDirection Direction); 231 232 /// Find llvm::Values referenced in GPU kernel. 233 /// 234 /// @param Kernel The kernel to scan for llvm::Values 235 /// 236 /// @returns A set of values referenced by the kernel. 237 SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel); 238 239 /// Compute the sizes of the execution grid for a given kernel. 240 /// 241 /// @param Kernel The kernel to compute grid sizes for. 242 /// 243 /// @returns A tuple with grid sizes for X and Y dimension 244 std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 245 246 /// Compute the sizes of the thread blocks for a given kernel. 247 /// 248 /// @param Kernel The kernel to compute thread block sizes for. 249 /// 250 /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 251 std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 252 253 /// Create kernel launch parameters. 254 /// 255 /// @param Kernel The kernel to create parameters for. 256 /// @param F The kernel function that has been created. 257 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 258 /// 259 /// @returns A stack allocated array with pointers to the parameter 260 /// values that are passed to the kernel. 261 Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 262 SetVector<Value *> SubtreeValues); 263 264 /// Create declarations for kernel variable. 265 /// 266 /// This includes shared memory declarations. 267 /// 268 /// @param Kernel The kernel definition to create variables for. 269 /// @param FN The function into which to generate the variables. 270 void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 271 272 /// Add CUDA annotations to module. 273 /// 274 /// Add a set of CUDA annotations that declares the maximal block dimensions 275 /// that will be used to execute the CUDA kernel. This allows the NVIDIA 276 /// PTX compiler to bound the number of allocated registers to ensure the 277 /// resulting kernel is known to run with up to as many block dimensions 278 /// as specified here. 279 /// 280 /// @param M The module to add the annotations to. 281 /// @param BlockDimX The size of block dimension X. 282 /// @param BlockDimY The size of block dimension Y. 283 /// @param BlockDimZ The size of block dimension Z. 284 void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 285 Value *BlockDimZ); 286 287 /// Create GPU kernel. 288 /// 289 /// Code generate the kernel described by @p KernelStmt. 290 /// 291 /// @param KernelStmt The ast node to generate kernel code for. 292 void createKernel(__isl_take isl_ast_node *KernelStmt); 293 294 /// Generate code that computes the size of an array. 295 /// 296 /// @param Array The array for which to compute a size. 297 Value *getArraySize(gpu_array_info *Array); 298 299 /// Generate code to compute the minimal offset at which an array is accessed. 300 /// 301 /// The offset of an array is the minimal array location accessed in a scop. 302 /// 303 /// Example: 304 /// 305 /// for (long i = 0; i < 100; i++) 306 /// A[i + 42] += ... 307 /// 308 /// getArrayOffset(A) results in 42. 309 /// 310 /// @param Array The array for which to compute the offset. 311 /// @returns An llvm::Value that contains the offset of the array. 312 Value *getArrayOffset(gpu_array_info *Array); 313 314 /// Prepare the kernel arguments for kernel code generation 315 /// 316 /// @param Kernel The kernel to generate code for. 317 /// @param FN The function created for the kernel. 318 void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 319 320 /// Create kernel function. 321 /// 322 /// Create a kernel function located in a newly created module that can serve 323 /// as target for device code generation. Set the Builder to point to the 324 /// start block of this newly created function. 325 /// 326 /// @param Kernel The kernel to generate code for. 327 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 328 void createKernelFunction(ppcg_kernel *Kernel, 329 SetVector<Value *> &SubtreeValues); 330 331 /// Create the declaration of a kernel function. 332 /// 333 /// The kernel function takes as arguments: 334 /// 335 /// - One i8 pointer for each external array reference used in the kernel. 336 /// - Host iterators 337 /// - Parameters 338 /// - Other LLVM Value references (TODO) 339 /// 340 /// @param Kernel The kernel to generate the function declaration for. 341 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 342 /// 343 /// @returns The newly declared function. 344 Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 345 SetVector<Value *> &SubtreeValues); 346 347 /// Insert intrinsic functions to obtain thread and block ids. 348 /// 349 /// @param The kernel to generate the intrinsic functions for. 350 void insertKernelIntrinsics(ppcg_kernel *Kernel); 351 352 /// Create a global-to-shared or shared-to-global copy statement. 353 /// 354 /// @param CopyStmt The copy statement to generate code for 355 void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 356 357 /// Create code for a ScopStmt called in @p Expr. 358 /// 359 /// @param Expr The expression containing the call. 360 /// @param KernelStmt The kernel statement referenced in the call. 361 void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 362 363 /// Create an in-kernel synchronization call. 364 void createKernelSync(); 365 366 /// Create a PTX assembly string for the current GPU kernel. 367 /// 368 /// @returns A string containing the corresponding PTX assembly code. 369 std::string createKernelASM(); 370 371 /// Remove references from the dominator tree to the kernel function @p F. 372 /// 373 /// @param F The function to remove references to. 374 void clearDominators(Function *F); 375 376 /// Remove references from scalar evolution to the kernel function @p F. 377 /// 378 /// @param F The function to remove references to. 379 void clearScalarEvolution(Function *F); 380 381 /// Remove references from loop info to the kernel function @p F. 382 /// 383 /// @param F The function to remove references to. 384 void clearLoops(Function *F); 385 386 /// Finalize the generation of the kernel function. 387 /// 388 /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 389 /// dump its IR to stderr. 390 /// 391 /// @returns The Assembly string of the kernel. 392 std::string finalizeKernelFunction(); 393 394 /// Finalize the generation of the kernel arguments. 395 /// 396 /// This function ensures that not-read-only scalars used in a kernel are 397 /// stored back to the global memory location they ared backed up with before 398 /// the kernel terminates. 399 /// 400 /// @params Kernel The kernel to finalize kernel arguments for. 401 void finalizeKernelArguments(ppcg_kernel *Kernel); 402 403 /// Create code that allocates memory to store arrays on device. 404 void allocateDeviceArrays(); 405 406 /// Free all allocated device arrays. 407 void freeDeviceArrays(); 408 409 /// Create a call to initialize the GPU context. 410 /// 411 /// @returns A pointer to the newly initialized context. 412 Value *createCallInitContext(); 413 414 /// Create a call to get the device pointer for a kernel allocation. 415 /// 416 /// @param Allocation The Polly GPU allocation 417 /// 418 /// @returns The device parameter corresponding to this allocation. 419 Value *createCallGetDevicePtr(Value *Allocation); 420 421 /// Create a call to free the GPU context. 422 /// 423 /// @param Context A pointer to an initialized GPU context. 424 void createCallFreeContext(Value *Context); 425 426 /// Create a call to allocate memory on the device. 427 /// 428 /// @param Size The size of memory to allocate 429 /// 430 /// @returns A pointer that identifies this allocation. 431 Value *createCallAllocateMemoryForDevice(Value *Size); 432 433 /// Create a call to free a device array. 434 /// 435 /// @param Array The device array to free. 436 void createCallFreeDeviceMemory(Value *Array); 437 438 /// Create a call to copy data from host to device. 439 /// 440 /// @param HostPtr A pointer to the host data that should be copied. 441 /// @param DevicePtr A device pointer specifying the location to copy to. 442 void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 443 Value *Size); 444 445 /// Create a call to copy data from device to host. 446 /// 447 /// @param DevicePtr A pointer to the device data that should be copied. 448 /// @param HostPtr A host pointer specifying the location to copy to. 449 void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 450 Value *Size); 451 452 /// Create a call to get a kernel from an assembly string. 453 /// 454 /// @param Buffer The string describing the kernel. 455 /// @param Entry The name of the kernel function to call. 456 /// 457 /// @returns A pointer to a kernel object 458 Value *createCallGetKernel(Value *Buffer, Value *Entry); 459 460 /// Create a call to free a GPU kernel. 461 /// 462 /// @param GPUKernel THe kernel to free. 463 void createCallFreeKernel(Value *GPUKernel); 464 465 /// Create a call to launch a GPU kernel. 466 /// 467 /// @param GPUKernel The kernel to launch. 468 /// @param GridDimX The size of the first grid dimension. 469 /// @param GridDimY The size of the second grid dimension. 470 /// @param GridBlockX The size of the first block dimension. 471 /// @param GridBlockY The size of the second block dimension. 472 /// @param GridBlockZ The size of the third block dimension. 473 /// @param Paramters A pointer to an array that contains itself pointers to 474 /// the parameter values passed for each kernel argument. 475 void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 476 Value *GridDimY, Value *BlockDimX, 477 Value *BlockDimY, Value *BlockDimZ, 478 Value *Parameters); 479 }; 480 481 void GPUNodeBuilder::initializeAfterRTH() { 482 BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 483 &*Builder.GetInsertPoint(), &DT, &LI); 484 NewBB->setName("polly.acc.initialize"); 485 Builder.SetInsertPoint(&NewBB->front()); 486 487 GPUContext = createCallInitContext(); 488 allocateDeviceArrays(); 489 } 490 491 void GPUNodeBuilder::finalize() { 492 freeDeviceArrays(); 493 createCallFreeContext(GPUContext); 494 IslNodeBuilder::finalize(); 495 } 496 497 void GPUNodeBuilder::allocateDeviceArrays() { 498 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 499 500 for (int i = 0; i < Prog->n_array; ++i) { 501 gpu_array_info *Array = &Prog->array[i]; 502 auto *ScopArray = (ScopArrayInfo *)Array->user; 503 std::string DevArrayName("p_dev_array_"); 504 DevArrayName.append(Array->name); 505 506 Value *ArraySize = getArraySize(Array); 507 Value *Offset = getArrayOffset(Array); 508 if (Offset) 509 ArraySize = Builder.CreateSub( 510 ArraySize, 511 Builder.CreateMul(Offset, 512 Builder.getInt64(ScopArray->getElemSizeInBytes()))); 513 Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 514 DevArray->setName(DevArrayName); 515 DeviceAllocations[ScopArray] = DevArray; 516 } 517 518 isl_ast_build_free(Build); 519 } 520 521 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 522 Value *BlockDimY, Value *BlockDimZ) { 523 auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 524 525 for (auto &F : *M) { 526 if (F.getCallingConv() != CallingConv::PTX_Kernel) 527 continue; 528 529 Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 530 531 Metadata *Elements[] = { 532 ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 533 ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 534 ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 535 ValueAsMetadata::get(V[2]), 536 }; 537 MDNode *Node = MDNode::get(M->getContext(), Elements); 538 AnnotationNode->addOperand(Node); 539 } 540 } 541 542 void GPUNodeBuilder::freeDeviceArrays() { 543 for (auto &Array : DeviceAllocations) 544 createCallFreeDeviceMemory(Array.second); 545 } 546 547 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 548 const char *Name = "polly_getKernel"; 549 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 550 Function *F = M->getFunction(Name); 551 552 // If F is not available, declare it. 553 if (!F) { 554 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 555 std::vector<Type *> Args; 556 Args.push_back(Builder.getInt8PtrTy()); 557 Args.push_back(Builder.getInt8PtrTy()); 558 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 559 F = Function::Create(Ty, Linkage, Name, M); 560 } 561 562 return Builder.CreateCall(F, {Buffer, Entry}); 563 } 564 565 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 566 const char *Name = "polly_getDevicePtr"; 567 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 568 Function *F = M->getFunction(Name); 569 570 // If F is not available, declare it. 571 if (!F) { 572 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 573 std::vector<Type *> Args; 574 Args.push_back(Builder.getInt8PtrTy()); 575 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 576 F = Function::Create(Ty, Linkage, Name, M); 577 } 578 579 return Builder.CreateCall(F, {Allocation}); 580 } 581 582 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 583 Value *GridDimY, Value *BlockDimX, 584 Value *BlockDimY, Value *BlockDimZ, 585 Value *Parameters) { 586 const char *Name = "polly_launchKernel"; 587 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 588 Function *F = M->getFunction(Name); 589 590 // If F is not available, declare it. 591 if (!F) { 592 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 593 std::vector<Type *> Args; 594 Args.push_back(Builder.getInt8PtrTy()); 595 Args.push_back(Builder.getInt32Ty()); 596 Args.push_back(Builder.getInt32Ty()); 597 Args.push_back(Builder.getInt32Ty()); 598 Args.push_back(Builder.getInt32Ty()); 599 Args.push_back(Builder.getInt32Ty()); 600 Args.push_back(Builder.getInt8PtrTy()); 601 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 602 F = Function::Create(Ty, Linkage, Name, M); 603 } 604 605 Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 606 BlockDimZ, Parameters}); 607 } 608 609 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 610 const char *Name = "polly_freeKernel"; 611 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 612 Function *F = M->getFunction(Name); 613 614 // If F is not available, declare it. 615 if (!F) { 616 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 617 std::vector<Type *> Args; 618 Args.push_back(Builder.getInt8PtrTy()); 619 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 620 F = Function::Create(Ty, Linkage, Name, M); 621 } 622 623 Builder.CreateCall(F, {GPUKernel}); 624 } 625 626 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 627 const char *Name = "polly_freeDeviceMemory"; 628 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 629 Function *F = M->getFunction(Name); 630 631 // If F is not available, declare it. 632 if (!F) { 633 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 634 std::vector<Type *> Args; 635 Args.push_back(Builder.getInt8PtrTy()); 636 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 637 F = Function::Create(Ty, Linkage, Name, M); 638 } 639 640 Builder.CreateCall(F, {Array}); 641 } 642 643 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 644 const char *Name = "polly_allocateMemoryForDevice"; 645 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 646 Function *F = M->getFunction(Name); 647 648 // If F is not available, declare it. 649 if (!F) { 650 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 651 std::vector<Type *> Args; 652 Args.push_back(Builder.getInt64Ty()); 653 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 654 F = Function::Create(Ty, Linkage, Name, M); 655 } 656 657 return Builder.CreateCall(F, {Size}); 658 } 659 660 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 661 Value *DeviceData, 662 Value *Size) { 663 const char *Name = "polly_copyFromHostToDevice"; 664 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 665 Function *F = M->getFunction(Name); 666 667 // If F is not available, declare it. 668 if (!F) { 669 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 670 std::vector<Type *> Args; 671 Args.push_back(Builder.getInt8PtrTy()); 672 Args.push_back(Builder.getInt8PtrTy()); 673 Args.push_back(Builder.getInt64Ty()); 674 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 675 F = Function::Create(Ty, Linkage, Name, M); 676 } 677 678 Builder.CreateCall(F, {HostData, DeviceData, Size}); 679 } 680 681 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 682 Value *HostData, 683 Value *Size) { 684 const char *Name = "polly_copyFromDeviceToHost"; 685 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 686 Function *F = M->getFunction(Name); 687 688 // If F is not available, declare it. 689 if (!F) { 690 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 691 std::vector<Type *> Args; 692 Args.push_back(Builder.getInt8PtrTy()); 693 Args.push_back(Builder.getInt8PtrTy()); 694 Args.push_back(Builder.getInt64Ty()); 695 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 696 F = Function::Create(Ty, Linkage, Name, M); 697 } 698 699 Builder.CreateCall(F, {DeviceData, HostData, Size}); 700 } 701 702 Value *GPUNodeBuilder::createCallInitContext() { 703 const char *Name = "polly_initContext"; 704 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 705 Function *F = M->getFunction(Name); 706 707 // If F is not available, declare it. 708 if (!F) { 709 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 710 std::vector<Type *> Args; 711 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 712 F = Function::Create(Ty, Linkage, Name, M); 713 } 714 715 return Builder.CreateCall(F, {}); 716 } 717 718 void GPUNodeBuilder::createCallFreeContext(Value *Context) { 719 const char *Name = "polly_freeContext"; 720 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 721 Function *F = M->getFunction(Name); 722 723 // If F is not available, declare it. 724 if (!F) { 725 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 726 std::vector<Type *> Args; 727 Args.push_back(Builder.getInt8PtrTy()); 728 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 729 F = Function::Create(Ty, Linkage, Name, M); 730 } 731 732 Builder.CreateCall(F, {Context}); 733 } 734 735 /// Check if one string is a prefix of another. 736 /// 737 /// @param String The string in which to look for the prefix. 738 /// @param Prefix The prefix to look for. 739 static bool isPrefix(std::string String, std::string Prefix) { 740 return String.find(Prefix) == 0; 741 } 742 743 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 744 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 745 Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 746 747 if (!gpu_array_is_scalar(Array)) { 748 auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]); 749 isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 750 751 for (unsigned int i = 1; i < Array->n_index; i++) { 752 isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]); 753 isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 754 Res = isl_ast_expr_mul(Res, Expr); 755 } 756 757 Value *NumElements = ExprBuilder.create(Res); 758 if (NumElements->getType() != ArraySize->getType()) 759 NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 760 ArraySize = Builder.CreateMul(ArraySize, NumElements); 761 } 762 isl_ast_build_free(Build); 763 return ArraySize; 764 } 765 766 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 767 if (gpu_array_is_scalar(Array)) 768 return nullptr; 769 770 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 771 772 isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 773 774 isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 775 776 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 777 ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 778 779 if (isl_set_is_subset(Min, ZeroSet)) { 780 isl_set_free(Min); 781 isl_set_free(ZeroSet); 782 isl_ast_build_free(Build); 783 return nullptr; 784 } 785 isl_set_free(ZeroSet); 786 787 isl_ast_expr *Result = 788 isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 789 790 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 791 if (i > 0) { 792 isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i - 1]); 793 isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 794 Result = isl_ast_expr_mul(Result, BExpr); 795 } 796 isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 797 isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 798 Result = isl_ast_expr_add(Result, MExpr); 799 } 800 801 Value *ResultValue = ExprBuilder.create(Result); 802 isl_set_free(Min); 803 isl_ast_build_free(Build); 804 805 return ResultValue; 806 } 807 808 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 809 enum DataDirection Direction) { 810 isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 811 isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 812 isl_id *Id = isl_ast_expr_get_id(Arg); 813 auto Array = (gpu_array_info *)isl_id_get_user(Id); 814 auto ScopArray = (ScopArrayInfo *)(Array->user); 815 816 Value *Size = getArraySize(Array); 817 Value *Offset = getArrayOffset(Array); 818 Value *DevPtr = DeviceAllocations[ScopArray]; 819 820 Value *HostPtr; 821 822 if (gpu_array_is_scalar(Array)) 823 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 824 else 825 HostPtr = ScopArray->getBasePtr(); 826 827 if (Offset) { 828 HostPtr = Builder.CreatePointerCast( 829 HostPtr, ScopArray->getElementType()->getPointerTo()); 830 HostPtr = Builder.CreateGEP(HostPtr, Offset); 831 } 832 833 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 834 835 if (Offset) { 836 Size = Builder.CreateSub( 837 Size, Builder.CreateMul( 838 Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 839 } 840 841 if (Direction == HOST_TO_DEVICE) 842 createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 843 else 844 createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 845 846 isl_id_free(Id); 847 isl_ast_expr_free(Arg); 848 isl_ast_expr_free(Expr); 849 isl_ast_node_free(TransferStmt); 850 } 851 852 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 853 isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 854 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 855 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 856 isl_id_free(Id); 857 isl_ast_expr_free(StmtExpr); 858 859 const char *Str = isl_id_get_name(Id); 860 if (!strcmp(Str, "kernel")) { 861 createKernel(UserStmt); 862 isl_ast_expr_free(Expr); 863 return; 864 } 865 866 if (isPrefix(Str, "to_device")) { 867 createDataTransfer(UserStmt, HOST_TO_DEVICE); 868 isl_ast_expr_free(Expr); 869 return; 870 } 871 872 if (isPrefix(Str, "from_device")) { 873 createDataTransfer(UserStmt, DEVICE_TO_HOST); 874 isl_ast_expr_free(Expr); 875 return; 876 } 877 878 isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 879 struct ppcg_kernel_stmt *KernelStmt = 880 (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 881 isl_id_free(Anno); 882 883 switch (KernelStmt->type) { 884 case ppcg_kernel_domain: 885 createScopStmt(Expr, KernelStmt); 886 isl_ast_node_free(UserStmt); 887 return; 888 case ppcg_kernel_copy: 889 createKernelCopy(KernelStmt); 890 isl_ast_expr_free(Expr); 891 isl_ast_node_free(UserStmt); 892 return; 893 case ppcg_kernel_sync: 894 createKernelSync(); 895 isl_ast_expr_free(Expr); 896 isl_ast_node_free(UserStmt); 897 return; 898 } 899 900 isl_ast_expr_free(Expr); 901 isl_ast_node_free(UserStmt); 902 return; 903 } 904 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 905 isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 906 LocalIndex = isl_ast_expr_address_of(LocalIndex); 907 Value *LocalAddr = ExprBuilder.create(LocalIndex); 908 isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 909 Index = isl_ast_expr_address_of(Index); 910 Value *GlobalAddr = ExprBuilder.create(Index); 911 912 if (KernelStmt->u.c.read) { 913 LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 914 Builder.CreateStore(Load, LocalAddr); 915 } else { 916 LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 917 Builder.CreateStore(Load, GlobalAddr); 918 } 919 } 920 921 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 922 ppcg_kernel_stmt *KernelStmt) { 923 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 924 isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 925 926 LoopToScevMapT LTS; 927 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 928 929 createSubstitutions(Expr, Stmt, LTS); 930 931 if (Stmt->isBlockStmt()) 932 BlockGen.copyStmt(*Stmt, LTS, Indexes); 933 else 934 RegionGen.copyStmt(*Stmt, LTS, Indexes); 935 } 936 937 void GPUNodeBuilder::createKernelSync() { 938 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 939 auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 940 Builder.CreateCall(Sync, {}); 941 } 942 943 /// Collect llvm::Values referenced from @p Node 944 /// 945 /// This function only applies to isl_ast_nodes that are user_nodes referring 946 /// to a ScopStmt. All other node types are ignore. 947 /// 948 /// @param Node The node to collect references for. 949 /// @param User A user pointer used as storage for the data that is collected. 950 /// 951 /// @returns isl_bool_true if data could be collected successfully. 952 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 953 if (isl_ast_node_get_type(Node) != isl_ast_node_user) 954 return isl_bool_true; 955 956 isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 957 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 958 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 959 const char *Str = isl_id_get_name(Id); 960 isl_id_free(Id); 961 isl_ast_expr_free(StmtExpr); 962 isl_ast_expr_free(Expr); 963 964 if (!isPrefix(Str, "Stmt")) 965 return isl_bool_true; 966 967 Id = isl_ast_node_get_annotation(Node); 968 auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 969 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 970 isl_id_free(Id); 971 972 addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 973 974 return isl_bool_true; 975 } 976 977 SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 978 SetVector<Value *> SubtreeValues; 979 SetVector<const SCEV *> SCEVs; 980 SetVector<const Loop *> Loops; 981 SubtreeReferences References = { 982 LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 983 984 for (const auto &I : IDToValue) 985 SubtreeValues.insert(I.second); 986 987 isl_ast_node_foreach_descendant_top_down( 988 Kernel->tree, collectReferencesInGPUStmt, &References); 989 990 for (const SCEV *Expr : SCEVs) 991 findValues(Expr, SE, SubtreeValues); 992 993 for (auto &SAI : S.arrays()) 994 SubtreeValues.remove(SAI->getBasePtr()); 995 996 isl_space *Space = S.getParamSpace(); 997 for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 998 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 999 assert(IDToValue.count(Id)); 1000 Value *Val = IDToValue[Id]; 1001 SubtreeValues.remove(Val); 1002 isl_id_free(Id); 1003 } 1004 isl_space_free(Space); 1005 1006 for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1007 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1008 assert(IDToValue.count(Id)); 1009 Value *Val = IDToValue[Id]; 1010 SubtreeValues.remove(Val); 1011 isl_id_free(Id); 1012 } 1013 1014 return SubtreeValues; 1015 } 1016 1017 void GPUNodeBuilder::clearDominators(Function *F) { 1018 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 1019 std::vector<BasicBlock *> Nodes; 1020 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 1021 Nodes.push_back(I->getBlock()); 1022 1023 for (BasicBlock *BB : Nodes) 1024 DT.eraseNode(BB); 1025 } 1026 1027 void GPUNodeBuilder::clearScalarEvolution(Function *F) { 1028 for (BasicBlock &BB : *F) { 1029 Loop *L = LI.getLoopFor(&BB); 1030 if (L) 1031 SE.forgetLoop(L); 1032 } 1033 } 1034 1035 void GPUNodeBuilder::clearLoops(Function *F) { 1036 for (BasicBlock &BB : *F) { 1037 Loop *L = LI.getLoopFor(&BB); 1038 if (L) 1039 SE.forgetLoop(L); 1040 LI.removeBlock(&BB); 1041 } 1042 } 1043 1044 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 1045 std::vector<Value *> Sizes; 1046 isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 1047 1048 for (long i = 0; i < Kernel->n_grid; i++) { 1049 isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 1050 isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 1051 Value *Res = ExprBuilder.create(GridSize); 1052 Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 1053 Sizes.push_back(Res); 1054 } 1055 isl_ast_build_free(Context); 1056 1057 for (long i = Kernel->n_grid; i < 3; i++) 1058 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1059 1060 return std::make_tuple(Sizes[0], Sizes[1]); 1061 } 1062 1063 std::tuple<Value *, Value *, Value *> 1064 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 1065 std::vector<Value *> Sizes; 1066 1067 for (long i = 0; i < Kernel->n_block; i++) { 1068 Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 1069 Sizes.push_back(Res); 1070 } 1071 1072 for (long i = Kernel->n_block; i < 3; i++) 1073 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1074 1075 return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 1076 } 1077 1078 Value * 1079 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 1080 SetVector<Value *> SubtreeValues) { 1081 Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 1082 std::distance(F->arg_begin(), F->arg_end())); 1083 1084 BasicBlock *EntryBlock = 1085 &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1086 auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 1087 std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 1088 Instruction *Parameters = new AllocaInst( 1089 ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 1090 1091 int Index = 0; 1092 for (long i = 0; i < Prog->n_array; i++) { 1093 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1094 continue; 1095 1096 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1097 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1098 1099 Value *DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 1100 DevArray = createCallGetDevicePtr(DevArray); 1101 1102 Value *Offset = getArrayOffset(&Prog->array[i]); 1103 1104 if (Offset) { 1105 DevArray = Builder.CreatePointerCast( 1106 DevArray, SAI->getElementType()->getPointerTo()); 1107 DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1108 DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1109 } 1110 Value *Slot = Builder.CreateGEP( 1111 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1112 1113 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1114 Value *ValPtr = BlockGen.getOrCreateAlloca(SAI); 1115 Value *ValPtrCast = 1116 Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1117 Builder.CreateStore(ValPtrCast, Slot); 1118 } else { 1119 Instruction *Param = 1120 new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 1121 Launch + "_param_" + std::to_string(Index), 1122 EntryBlock->getTerminator()); 1123 Builder.CreateStore(DevArray, Param); 1124 Value *ParamTyped = 1125 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1126 Builder.CreateStore(ParamTyped, Slot); 1127 } 1128 Index++; 1129 } 1130 1131 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1132 1133 for (long i = 0; i < NumHostIters; i++) { 1134 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1135 Value *Val = IDToValue[Id]; 1136 isl_id_free(Id); 1137 Instruction *Param = 1138 new AllocaInst(Val->getType(), AddressSpace, 1139 Launch + "_param_" + std::to_string(Index), 1140 EntryBlock->getTerminator()); 1141 Builder.CreateStore(Val, Param); 1142 Value *Slot = Builder.CreateGEP( 1143 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1144 Value *ParamTyped = 1145 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1146 Builder.CreateStore(ParamTyped, Slot); 1147 Index++; 1148 } 1149 1150 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1151 1152 for (long i = 0; i < NumVars; i++) { 1153 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1154 Value *Val = IDToValue[Id]; 1155 isl_id_free(Id); 1156 Instruction *Param = 1157 new AllocaInst(Val->getType(), AddressSpace, 1158 Launch + "_param_" + std::to_string(Index), 1159 EntryBlock->getTerminator()); 1160 Builder.CreateStore(Val, Param); 1161 Value *Slot = Builder.CreateGEP( 1162 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1163 Value *ParamTyped = 1164 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1165 Builder.CreateStore(ParamTyped, Slot); 1166 Index++; 1167 } 1168 1169 for (auto Val : SubtreeValues) { 1170 Instruction *Param = 1171 new AllocaInst(Val->getType(), AddressSpace, 1172 Launch + "_param_" + std::to_string(Index), 1173 EntryBlock->getTerminator()); 1174 Builder.CreateStore(Val, Param); 1175 Value *Slot = Builder.CreateGEP( 1176 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1177 Value *ParamTyped = 1178 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1179 Builder.CreateStore(ParamTyped, Slot); 1180 Index++; 1181 } 1182 1183 auto Location = EntryBlock->getTerminator(); 1184 return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 1185 Launch + "_params_i8ptr", Location); 1186 } 1187 1188 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 1189 isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 1190 ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 1191 isl_id_free(Id); 1192 isl_ast_node_free(KernelStmt); 1193 1194 if (Kernel->n_grid > 1) 1195 DeepestParallel = 1196 std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1197 else 1198 DeepestSequential = 1199 std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1200 1201 Value *BlockDimX, *BlockDimY, *BlockDimZ; 1202 std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1203 1204 SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel); 1205 1206 assert(Kernel->tree && "Device AST of kernel node is empty"); 1207 1208 Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1209 IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1210 ValueMapT HostValueMap = ValueMap; 1211 BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1212 ScalarMap.clear(); 1213 1214 SetVector<const Loop *> Loops; 1215 1216 // Create for all loops we depend on values that contain the current loop 1217 // iteration. These values are necessary to generate code for SCEVs that 1218 // depend on such loops. As a result we need to pass them to the subfunction. 1219 for (const Loop *L : Loops) { 1220 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1221 SE.getUnknown(Builder.getInt64(1)), 1222 L, SCEV::FlagAnyWrap); 1223 Value *V = generateSCEV(OuterLIV); 1224 OutsideLoopIterations[L] = SE.getUnknown(V); 1225 SubtreeValues.insert(V); 1226 } 1227 1228 createKernelFunction(Kernel, SubtreeValues); 1229 1230 create(isl_ast_node_copy(Kernel->tree)); 1231 1232 finalizeKernelArguments(Kernel); 1233 Function *F = Builder.GetInsertBlock()->getParent(); 1234 addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 1235 clearDominators(F); 1236 clearScalarEvolution(F); 1237 clearLoops(F); 1238 1239 IDToValue = HostIDs; 1240 1241 ValueMap = std::move(HostValueMap); 1242 ScalarMap = std::move(HostScalarMap); 1243 EscapeMap.clear(); 1244 IDToSAI.clear(); 1245 Annotator.resetAlternativeAliasBases(); 1246 for (auto &BasePtr : LocalArrays) 1247 S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 1248 LocalArrays.clear(); 1249 1250 std::string ASMString = finalizeKernelFunction(); 1251 Builder.SetInsertPoint(&HostInsertPoint); 1252 Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 1253 1254 std::string Name = "kernel_" + std::to_string(Kernel->id); 1255 Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 1256 Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 1257 Value *GPUKernel = createCallGetKernel(KernelString, NameString); 1258 1259 Value *GridDimX, *GridDimY; 1260 std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 1261 1262 createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 1263 BlockDimZ, Parameters); 1264 createCallFreeKernel(GPUKernel); 1265 1266 for (auto Id : KernelIds) 1267 isl_id_free(Id); 1268 1269 KernelIds.clear(); 1270 } 1271 1272 /// Compute the DataLayout string for the NVPTX backend. 1273 /// 1274 /// @param is64Bit Are we looking for a 64 bit architecture? 1275 static std::string computeNVPTXDataLayout(bool is64Bit) { 1276 std::string Ret = ""; 1277 1278 if (!is64Bit) { 1279 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1280 "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1281 "64-v128:128:128-n16:32:64"; 1282 } else { 1283 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1284 "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1285 "64-v128:128:128-n16:32:64"; 1286 } 1287 1288 return Ret; 1289 } 1290 1291 Function * 1292 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1293 SetVector<Value *> &SubtreeValues) { 1294 std::vector<Type *> Args; 1295 std::string Identifier = "kernel_" + std::to_string(Kernel->id); 1296 1297 for (long i = 0; i < Prog->n_array; i++) { 1298 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1299 continue; 1300 1301 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1302 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1303 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1304 Args.push_back(SAI->getElementType()); 1305 } else { 1306 static const int UseGlobalMemory = 1; 1307 Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 1308 } 1309 } 1310 1311 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1312 1313 for (long i = 0; i < NumHostIters; i++) 1314 Args.push_back(Builder.getInt64Ty()); 1315 1316 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1317 1318 for (long i = 0; i < NumVars; i++) { 1319 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1320 Value *Val = IDToValue[Id]; 1321 isl_id_free(Id); 1322 Args.push_back(Val->getType()); 1323 } 1324 1325 for (auto *V : SubtreeValues) 1326 Args.push_back(V->getType()); 1327 1328 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1329 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1330 GPUModule.get()); 1331 FN->setCallingConv(CallingConv::PTX_Kernel); 1332 1333 auto Arg = FN->arg_begin(); 1334 for (long i = 0; i < Kernel->n_array; i++) { 1335 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1336 continue; 1337 1338 Arg->setName(Kernel->array[i].array->name); 1339 1340 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1341 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1342 Type *EleTy = SAI->getElementType(); 1343 Value *Val = &*Arg; 1344 SmallVector<const SCEV *, 4> Sizes; 1345 isl_ast_build *Build = 1346 isl_ast_build_from_context(isl_set_copy(Prog->context)); 1347 Sizes.push_back(nullptr); 1348 for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1349 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1350 Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1351 auto V = ExprBuilder.create(DimSize); 1352 Sizes.push_back(SE.getSCEV(V)); 1353 } 1354 const ScopArrayInfo *SAIRep = 1355 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 1356 LocalArrays.push_back(Val); 1357 1358 isl_ast_build_free(Build); 1359 KernelIds.push_back(Id); 1360 IDToSAI[Id] = SAIRep; 1361 Arg++; 1362 } 1363 1364 for (long i = 0; i < NumHostIters; i++) { 1365 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1366 Arg->setName(isl_id_get_name(Id)); 1367 IDToValue[Id] = &*Arg; 1368 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1369 Arg++; 1370 } 1371 1372 for (long i = 0; i < NumVars; i++) { 1373 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1374 Arg->setName(isl_id_get_name(Id)); 1375 Value *Val = IDToValue[Id]; 1376 ValueMap[Val] = &*Arg; 1377 IDToValue[Id] = &*Arg; 1378 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1379 Arg++; 1380 } 1381 1382 for (auto *V : SubtreeValues) { 1383 Arg->setName(V->getName()); 1384 ValueMap[V] = &*Arg; 1385 Arg++; 1386 } 1387 1388 return FN; 1389 } 1390 1391 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1392 Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x, 1393 Intrinsic::nvvm_read_ptx_sreg_ctaid_y}; 1394 1395 Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x, 1396 Intrinsic::nvvm_read_ptx_sreg_tid_y, 1397 Intrinsic::nvvm_read_ptx_sreg_tid_z}; 1398 1399 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1400 std::string Name = isl_id_get_name(Id); 1401 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1402 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1403 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1404 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1405 IDToValue[Id] = Val; 1406 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1407 }; 1408 1409 for (int i = 0; i < Kernel->n_grid; ++i) { 1410 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1411 addId(Id, IntrinsicsBID[i]); 1412 } 1413 1414 for (int i = 0; i < Kernel->n_block; ++i) { 1415 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1416 addId(Id, IntrinsicsTID[i]); 1417 } 1418 } 1419 1420 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 1421 auto Arg = FN->arg_begin(); 1422 for (long i = 0; i < Kernel->n_array; i++) { 1423 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1424 continue; 1425 1426 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1427 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1428 isl_id_free(Id); 1429 1430 if (SAI->getNumberOfDimensions() > 0) { 1431 Arg++; 1432 continue; 1433 } 1434 1435 Value *Val = &*Arg; 1436 1437 if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 1438 Type *TypePtr = SAI->getElementType()->getPointerTo(); 1439 Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1440 Val = Builder.CreateLoad(TypedArgPtr); 1441 } 1442 1443 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 1444 Builder.CreateStore(Val, Alloca); 1445 1446 Arg++; 1447 } 1448 } 1449 1450 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 1451 auto *FN = Builder.GetInsertBlock()->getParent(); 1452 auto Arg = FN->arg_begin(); 1453 1454 bool StoredScalar = false; 1455 for (long i = 0; i < Kernel->n_array; i++) { 1456 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1457 continue; 1458 1459 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1460 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1461 isl_id_free(Id); 1462 1463 if (SAI->getNumberOfDimensions() > 0) { 1464 Arg++; 1465 continue; 1466 } 1467 1468 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1469 Arg++; 1470 continue; 1471 } 1472 1473 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 1474 Value *ArgPtr = &*Arg; 1475 Type *TypePtr = SAI->getElementType()->getPointerTo(); 1476 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 1477 Value *Val = Builder.CreateLoad(Alloca); 1478 Builder.CreateStore(Val, TypedArgPtr); 1479 StoredScalar = true; 1480 1481 Arg++; 1482 } 1483 1484 if (StoredScalar) 1485 /// In case more than one thread contains scalar stores, the generated 1486 /// code might be incorrect, if we only store at the end of the kernel. 1487 /// To support this case we need to store these scalars back at each 1488 /// memory store or at least before each kernel barrier. 1489 if (Kernel->n_block != 0 || Kernel->n_grid != 0) 1490 BuildSuccessful = 0; 1491 } 1492 1493 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1494 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1495 1496 for (int i = 0; i < Kernel->n_var; ++i) { 1497 struct ppcg_kernel_var &Var = Kernel->var[i]; 1498 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1499 Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1500 1501 Type *ArrayTy = EleTy; 1502 SmallVector<const SCEV *, 4> Sizes; 1503 1504 Sizes.push_back(nullptr); 1505 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1506 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1507 long Bound = isl_val_get_num_si(Val); 1508 isl_val_free(Val); 1509 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1510 } 1511 1512 for (int j = Var.array->n_index - 1; j >= 0; --j) { 1513 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1514 long Bound = isl_val_get_num_si(Val); 1515 isl_val_free(Val); 1516 ArrayTy = ArrayType::get(ArrayTy, Bound); 1517 } 1518 1519 const ScopArrayInfo *SAI; 1520 Value *Allocation; 1521 if (Var.type == ppcg_access_shared) { 1522 auto GlobalVar = new GlobalVariable( 1523 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1524 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1525 GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1526 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1527 1528 Allocation = GlobalVar; 1529 } else if (Var.type == ppcg_access_private) { 1530 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1531 } else { 1532 llvm_unreachable("unknown variable type"); 1533 } 1534 SAI = 1535 S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1536 Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1537 IDToValue[Id] = Allocation; 1538 LocalArrays.push_back(Allocation); 1539 KernelIds.push_back(Id); 1540 IDToSAI[Id] = SAI; 1541 } 1542 } 1543 1544 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel, 1545 SetVector<Value *> &SubtreeValues) { 1546 1547 std::string Identifier = "kernel_" + std::to_string(Kernel->id); 1548 GPUModule.reset(new Module(Identifier, Builder.getContext())); 1549 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 1550 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 1551 1552 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 1553 1554 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 1555 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 1556 1557 DT.addNewBlock(EntryBlock, PrevBlock); 1558 1559 Builder.SetInsertPoint(EntryBlock); 1560 Builder.CreateRetVoid(); 1561 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1562 1563 ScopDetection::markFunctionAsInvalid(FN); 1564 1565 prepareKernelArguments(Kernel, FN); 1566 createKernelVariables(Kernel, FN); 1567 insertKernelIntrinsics(Kernel); 1568 } 1569 1570 std::string GPUNodeBuilder::createKernelASM() { 1571 llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda")); 1572 std::string ErrMsg; 1573 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 1574 1575 if (!GPUTarget) { 1576 errs() << ErrMsg << "\n"; 1577 return ""; 1578 } 1579 1580 TargetOptions Options; 1581 Options.UnsafeFPMath = FastMath; 1582 std::unique_ptr<TargetMachine> TargetM( 1583 GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "", 1584 Options, Optional<Reloc::Model>())); 1585 1586 SmallString<0> ASMString; 1587 raw_svector_ostream ASMStream(ASMString); 1588 llvm::legacy::PassManager PM; 1589 1590 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 1591 1592 if (TargetM->addPassesToEmitFile( 1593 PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 1594 errs() << "The target does not support generation of this file type!\n"; 1595 return ""; 1596 } 1597 1598 PM.run(*GPUModule); 1599 1600 return ASMStream.str(); 1601 } 1602 1603 std::string GPUNodeBuilder::finalizeKernelFunction() { 1604 if (verifyModule(*GPUModule)) { 1605 BuildSuccessful = false; 1606 return ""; 1607 } 1608 1609 if (DumpKernelIR) 1610 outs() << *GPUModule << "\n"; 1611 1612 // Optimize module. 1613 llvm::legacy::PassManager OptPasses; 1614 PassManagerBuilder PassBuilder; 1615 PassBuilder.OptLevel = 3; 1616 PassBuilder.SizeLevel = 0; 1617 PassBuilder.populateModulePassManager(OptPasses); 1618 OptPasses.run(*GPUModule); 1619 1620 std::string Assembly = createKernelASM(); 1621 1622 if (DumpKernelASM) 1623 outs() << Assembly << "\n"; 1624 1625 GPUModule.release(); 1626 KernelIDs.clear(); 1627 1628 return Assembly; 1629 } 1630 1631 namespace { 1632 class PPCGCodeGeneration : public ScopPass { 1633 public: 1634 static char ID; 1635 1636 /// The scop that is currently processed. 1637 Scop *S; 1638 1639 LoopInfo *LI; 1640 DominatorTree *DT; 1641 ScalarEvolution *SE; 1642 const DataLayout *DL; 1643 RegionInfo *RI; 1644 1645 PPCGCodeGeneration() : ScopPass(ID) {} 1646 1647 /// Construct compilation options for PPCG. 1648 /// 1649 /// @returns The compilation options. 1650 ppcg_options *createPPCGOptions() { 1651 auto DebugOptions = 1652 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 1653 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 1654 1655 DebugOptions->dump_schedule_constraints = false; 1656 DebugOptions->dump_schedule = false; 1657 DebugOptions->dump_final_schedule = false; 1658 DebugOptions->dump_sizes = false; 1659 DebugOptions->verbose = false; 1660 1661 Options->debug = DebugOptions; 1662 1663 Options->reschedule = true; 1664 Options->scale_tile_loops = false; 1665 Options->wrap = false; 1666 1667 Options->non_negative_parameters = false; 1668 Options->ctx = nullptr; 1669 Options->sizes = nullptr; 1670 1671 Options->tile_size = 32; 1672 1673 Options->use_private_memory = PrivateMemory; 1674 Options->use_shared_memory = SharedMemory; 1675 Options->max_shared_memory = 48 * 1024; 1676 1677 Options->target = PPCG_TARGET_CUDA; 1678 Options->openmp = false; 1679 Options->linearize_device_arrays = true; 1680 Options->live_range_reordering = false; 1681 1682 Options->opencl_compiler_options = nullptr; 1683 Options->opencl_use_gpu = false; 1684 Options->opencl_n_include_file = 0; 1685 Options->opencl_include_files = nullptr; 1686 Options->opencl_print_kernel_types = false; 1687 Options->opencl_embed_kernel_code = false; 1688 1689 Options->save_schedule_file = nullptr; 1690 Options->load_schedule_file = nullptr; 1691 1692 return Options; 1693 } 1694 1695 /// Get a tagged access relation containing all accesses of type @p AccessTy. 1696 /// 1697 /// Instead of a normal access of the form: 1698 /// 1699 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 1700 /// 1701 /// a tagged access has the form 1702 /// 1703 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 1704 /// 1705 /// where 'id' is an additional space that references the memory access that 1706 /// triggered the access. 1707 /// 1708 /// @param AccessTy The type of the memory accesses to collect. 1709 /// 1710 /// @return The relation describing all tagged memory accesses. 1711 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 1712 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 1713 1714 for (auto &Stmt : *S) 1715 for (auto &Acc : Stmt) 1716 if (Acc->getType() == AccessTy) { 1717 isl_map *Relation = Acc->getAccessRelation(); 1718 Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 1719 1720 isl_space *Space = isl_map_get_space(Relation); 1721 Space = isl_space_range(Space); 1722 Space = isl_space_from_range(Space); 1723 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 1724 isl_map *Universe = isl_map_universe(Space); 1725 Relation = isl_map_domain_product(Relation, Universe); 1726 Accesses = isl_union_map_add_map(Accesses, Relation); 1727 } 1728 1729 return Accesses; 1730 } 1731 1732 /// Get the set of all read accesses, tagged with the access id. 1733 /// 1734 /// @see getTaggedAccesses 1735 isl_union_map *getTaggedReads() { 1736 return getTaggedAccesses(MemoryAccess::READ); 1737 } 1738 1739 /// Get the set of all may (and must) accesses, tagged with the access id. 1740 /// 1741 /// @see getTaggedAccesses 1742 isl_union_map *getTaggedMayWrites() { 1743 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 1744 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 1745 } 1746 1747 /// Get the set of all must accesses, tagged with the access id. 1748 /// 1749 /// @see getTaggedAccesses 1750 isl_union_map *getTaggedMustWrites() { 1751 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 1752 } 1753 1754 /// Collect parameter and array names as isl_ids. 1755 /// 1756 /// To reason about the different parameters and arrays used, ppcg requires 1757 /// a list of all isl_ids in use. As PPCG traditionally performs 1758 /// source-to-source compilation each of these isl_ids is mapped to the 1759 /// expression that represents it. As we do not have a corresponding 1760 /// expression in Polly, we just map each id to a 'zero' expression to match 1761 /// the data format that ppcg expects. 1762 /// 1763 /// @returns Retun a map from collected ids to 'zero' ast expressions. 1764 __isl_give isl_id_to_ast_expr *getNames() { 1765 auto *Names = isl_id_to_ast_expr_alloc( 1766 S->getIslCtx(), 1767 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 1768 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 1769 auto *Space = S->getParamSpace(); 1770 1771 for (int I = 0, E = S->getNumParams(); I < E; ++I) { 1772 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 1773 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1774 } 1775 1776 for (auto &Array : S->arrays()) { 1777 auto Id = Array->getBasePtrId(); 1778 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1779 } 1780 1781 isl_space_free(Space); 1782 isl_ast_expr_free(Zero); 1783 1784 return Names; 1785 } 1786 1787 /// Create a new PPCG scop from the current scop. 1788 /// 1789 /// The PPCG scop is initialized with data from the current polly::Scop. From 1790 /// this initial data, the data-dependences in the PPCG scop are initialized. 1791 /// We do not use Polly's dependence analysis for now, to ensure we match 1792 /// the PPCG default behaviour more closely. 1793 /// 1794 /// @returns A new ppcg scop. 1795 ppcg_scop *createPPCGScop() { 1796 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 1797 1798 PPCGScop->options = createPPCGOptions(); 1799 1800 PPCGScop->start = 0; 1801 PPCGScop->end = 0; 1802 1803 PPCGScop->context = S->getContext(); 1804 PPCGScop->domain = S->getDomains(); 1805 PPCGScop->call = nullptr; 1806 PPCGScop->tagged_reads = getTaggedReads(); 1807 PPCGScop->reads = S->getReads(); 1808 PPCGScop->live_in = nullptr; 1809 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 1810 PPCGScop->may_writes = S->getWrites(); 1811 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 1812 PPCGScop->must_writes = S->getMustWrites(); 1813 PPCGScop->live_out = nullptr; 1814 PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace()); 1815 PPCGScop->tagger = nullptr; 1816 1817 PPCGScop->independence = nullptr; 1818 PPCGScop->dep_flow = nullptr; 1819 PPCGScop->tagged_dep_flow = nullptr; 1820 PPCGScop->dep_false = nullptr; 1821 PPCGScop->dep_forced = nullptr; 1822 PPCGScop->dep_order = nullptr; 1823 PPCGScop->tagged_dep_order = nullptr; 1824 1825 PPCGScop->schedule = S->getScheduleTree(); 1826 PPCGScop->names = getNames(); 1827 1828 PPCGScop->pet = nullptr; 1829 1830 compute_tagger(PPCGScop); 1831 compute_dependences(PPCGScop); 1832 1833 return PPCGScop; 1834 } 1835 1836 /// Collect the array acesses in a statement. 1837 /// 1838 /// @param Stmt The statement for which to collect the accesses. 1839 /// 1840 /// @returns A list of array accesses. 1841 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 1842 gpu_stmt_access *Accesses = nullptr; 1843 1844 for (MemoryAccess *Acc : Stmt) { 1845 auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 1846 Access->read = Acc->isRead(); 1847 Access->write = Acc->isWrite(); 1848 Access->access = Acc->getAccessRelation(); 1849 isl_space *Space = isl_map_get_space(Access->access); 1850 Space = isl_space_range(Space); 1851 Space = isl_space_from_range(Space); 1852 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 1853 isl_map *Universe = isl_map_universe(Space); 1854 Access->tagged_access = 1855 isl_map_domain_product(Acc->getAccessRelation(), Universe); 1856 Access->exact_write = !Acc->isMayWrite(); 1857 Access->ref_id = Acc->getId(); 1858 Access->next = Accesses; 1859 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 1860 Accesses = Access; 1861 } 1862 1863 return Accesses; 1864 } 1865 1866 /// Collect the list of GPU statements. 1867 /// 1868 /// Each statement has an id, a pointer to the underlying data structure, 1869 /// as well as a list with all memory accesses. 1870 /// 1871 /// TODO: Initialize the list of memory accesses. 1872 /// 1873 /// @returns A linked-list of statements. 1874 gpu_stmt *getStatements() { 1875 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 1876 std::distance(S->begin(), S->end())); 1877 1878 int i = 0; 1879 for (auto &Stmt : *S) { 1880 gpu_stmt *GPUStmt = &Stmts[i]; 1881 1882 GPUStmt->id = Stmt.getDomainId(); 1883 1884 // We use the pet stmt pointer to keep track of the Polly statements. 1885 GPUStmt->stmt = (pet_stmt *)&Stmt; 1886 GPUStmt->accesses = getStmtAccesses(Stmt); 1887 i++; 1888 } 1889 1890 return Stmts; 1891 } 1892 1893 /// Derive the extent of an array. 1894 /// 1895 /// The extent of an array is the set of elements that are within the 1896 /// accessed array. For the inner dimensions, the extent constraints are 1897 /// 0 and the size of the corresponding array dimension. For the first 1898 /// (outermost) dimension, the extent constraints are the minimal and maximal 1899 /// subscript value for the first dimension. 1900 /// 1901 /// @param Array The array to derive the extent for. 1902 /// 1903 /// @returns An isl_set describing the extent of the array. 1904 __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 1905 unsigned NumDims = Array->getNumberOfDimensions(); 1906 isl_union_map *Accesses = S->getAccesses(); 1907 Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 1908 Accesses = isl_union_map_detect_equalities(Accesses); 1909 isl_union_set *AccessUSet = isl_union_map_range(Accesses); 1910 AccessUSet = isl_union_set_coalesce(AccessUSet); 1911 AccessUSet = isl_union_set_detect_equalities(AccessUSet); 1912 AccessUSet = isl_union_set_coalesce(AccessUSet); 1913 1914 if (isl_union_set_is_empty(AccessUSet)) { 1915 isl_union_set_free(AccessUSet); 1916 return isl_set_empty(Array->getSpace()); 1917 } 1918 1919 if (Array->getNumberOfDimensions() == 0) { 1920 isl_union_set_free(AccessUSet); 1921 return isl_set_universe(Array->getSpace()); 1922 } 1923 1924 isl_set *AccessSet = 1925 isl_union_set_extract_set(AccessUSet, Array->getSpace()); 1926 1927 isl_union_set_free(AccessUSet); 1928 isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 1929 1930 isl_pw_aff *Val = 1931 isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 1932 1933 isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 1934 isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 1935 OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 1936 isl_pw_aff_dim(Val, isl_dim_in)); 1937 OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 1938 isl_pw_aff_dim(Val, isl_dim_in)); 1939 OuterMin = 1940 isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 1941 OuterMax = 1942 isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 1943 1944 isl_set *Extent = isl_set_universe(Array->getSpace()); 1945 1946 Extent = isl_set_intersect( 1947 Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 1948 Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 1949 1950 for (unsigned i = 1; i < NumDims; ++i) 1951 Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 1952 1953 for (unsigned i = 1; i < NumDims; ++i) { 1954 isl_pw_aff *PwAff = 1955 const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 1956 isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 1957 isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 1958 PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 1959 isl_pw_aff_dim(Val, isl_dim_in)); 1960 PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 1961 isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 1962 auto *Set = isl_pw_aff_gt_set(PwAff, Val); 1963 Extent = isl_set_intersect(Set, Extent); 1964 } 1965 1966 return Extent; 1967 } 1968 1969 /// Derive the bounds of an array. 1970 /// 1971 /// For the first dimension we derive the bound of the array from the extent 1972 /// of this dimension. For inner dimensions we obtain their size directly from 1973 /// ScopArrayInfo. 1974 /// 1975 /// @param PPCGArray The array to compute bounds for. 1976 /// @param Array The polly array from which to take the information. 1977 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 1978 if (PPCGArray.n_index > 0) { 1979 if (isl_set_is_empty(PPCGArray.extent)) { 1980 isl_set *Dom = isl_set_copy(PPCGArray.extent); 1981 isl_local_space *LS = isl_local_space_from_space( 1982 isl_space_params(isl_set_get_space(Dom))); 1983 isl_set_free(Dom); 1984 isl_aff *Zero = isl_aff_zero_on_domain(LS); 1985 PPCGArray.bound[0] = isl_pw_aff_from_aff(Zero); 1986 } else { 1987 isl_set *Dom = isl_set_copy(PPCGArray.extent); 1988 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 1989 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 1990 isl_set_free(Dom); 1991 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 1992 isl_local_space *LS = 1993 isl_local_space_from_space(isl_set_get_space(Dom)); 1994 isl_aff *One = isl_aff_zero_on_domain(LS); 1995 One = isl_aff_add_constant_si(One, 1); 1996 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 1997 Bound = isl_pw_aff_gist(Bound, S->getContext()); 1998 PPCGArray.bound[0] = Bound; 1999 } 2000 } 2001 2002 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2003 isl_pw_aff *Bound = Array->getDimensionSizePw(i); 2004 auto LS = isl_pw_aff_get_domain_space(Bound); 2005 auto Aff = isl_multi_aff_zero(LS); 2006 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2007 PPCGArray.bound[i] = Bound; 2008 } 2009 } 2010 2011 /// Create the arrays for @p PPCGProg. 2012 /// 2013 /// @param PPCGProg The program to compute the arrays for. 2014 void createArrays(gpu_prog *PPCGProg) { 2015 int i = 0; 2016 for (auto &Array : S->arrays()) { 2017 std::string TypeName; 2018 raw_string_ostream OS(TypeName); 2019 2020 OS << *Array->getElementType(); 2021 TypeName = OS.str(); 2022 2023 gpu_array_info &PPCGArray = PPCGProg->array[i]; 2024 2025 PPCGArray.space = Array->getSpace(); 2026 PPCGArray.type = strdup(TypeName.c_str()); 2027 PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 2028 PPCGArray.name = strdup(Array->getName().c_str()); 2029 PPCGArray.extent = nullptr; 2030 PPCGArray.n_index = Array->getNumberOfDimensions(); 2031 PPCGArray.bound = 2032 isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 2033 PPCGArray.extent = getExtent(Array); 2034 PPCGArray.n_ref = 0; 2035 PPCGArray.refs = nullptr; 2036 PPCGArray.accessed = true; 2037 PPCGArray.read_only_scalar = 2038 Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 2039 PPCGArray.has_compound_element = false; 2040 PPCGArray.local = false; 2041 PPCGArray.declare_local = false; 2042 PPCGArray.global = false; 2043 PPCGArray.linearize = false; 2044 PPCGArray.dep_order = nullptr; 2045 PPCGArray.user = Array; 2046 2047 setArrayBounds(PPCGArray, Array); 2048 i++; 2049 2050 collect_references(PPCGProg, &PPCGArray); 2051 } 2052 } 2053 2054 /// Create an identity map between the arrays in the scop. 2055 /// 2056 /// @returns An identity map between the arrays in the scop. 2057 isl_union_map *getArrayIdentity() { 2058 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 2059 2060 for (auto &Array : S->arrays()) { 2061 isl_space *Space = Array->getSpace(); 2062 Space = isl_space_map_from_set(Space); 2063 isl_map *Identity = isl_map_identity(Space); 2064 Maps = isl_union_map_add_map(Maps, Identity); 2065 } 2066 2067 return Maps; 2068 } 2069 2070 /// Create a default-initialized PPCG GPU program. 2071 /// 2072 /// @returns A new gpu grogram description. 2073 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2074 2075 if (!PPCGScop) 2076 return nullptr; 2077 2078 auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2079 2080 PPCGProg->ctx = S->getIslCtx(); 2081 PPCGProg->scop = PPCGScop; 2082 PPCGProg->context = isl_set_copy(PPCGScop->context); 2083 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 2084 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 2085 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 2086 PPCGProg->tagged_must_kill = 2087 isl_union_map_copy(PPCGScop->tagged_must_kills); 2088 PPCGProg->to_inner = getArrayIdentity(); 2089 PPCGProg->to_outer = getArrayIdentity(); 2090 PPCGProg->any_to_outer = nullptr; 2091 PPCGProg->array_order = nullptr; 2092 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 2093 PPCGProg->stmts = getStatements(); 2094 PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 2095 PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 2096 PPCGProg->n_array); 2097 2098 createArrays(PPCGProg); 2099 2100 PPCGProg->may_persist = compute_may_persist(PPCGProg); 2101 2102 return PPCGProg; 2103 } 2104 2105 struct PrintGPUUserData { 2106 struct cuda_info *CudaInfo; 2107 struct gpu_prog *PPCGProg; 2108 std::vector<ppcg_kernel *> Kernels; 2109 }; 2110 2111 /// Print a user statement node in the host code. 2112 /// 2113 /// We use ppcg's printing facilities to print the actual statement and 2114 /// additionally build up a list of all kernels that are encountered in the 2115 /// host ast. 2116 /// 2117 /// @param P The printer to print to 2118 /// @param Options The printing options to use 2119 /// @param Node The node to print 2120 /// @param User A user pointer to carry additional data. This pointer is 2121 /// expected to be of type PrintGPUUserData. 2122 /// 2123 /// @returns A printer to which the output has been printed. 2124 static __isl_give isl_printer * 2125 printHostUser(__isl_take isl_printer *P, 2126 __isl_take isl_ast_print_options *Options, 2127 __isl_take isl_ast_node *Node, void *User) { 2128 auto Data = (struct PrintGPUUserData *)User; 2129 auto Id = isl_ast_node_get_annotation(Node); 2130 2131 if (Id) { 2132 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 2133 2134 // If this is a user statement, format it ourselves as ppcg would 2135 // otherwise try to call pet functionality that is not available in 2136 // Polly. 2137 if (IsUser) { 2138 P = isl_printer_start_line(P); 2139 P = isl_printer_print_ast_node(P, Node); 2140 P = isl_printer_end_line(P); 2141 isl_id_free(Id); 2142 isl_ast_print_options_free(Options); 2143 return P; 2144 } 2145 2146 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 2147 isl_id_free(Id); 2148 Data->Kernels.push_back(Kernel); 2149 } 2150 2151 return print_host_user(P, Options, Node, User); 2152 } 2153 2154 /// Print C code corresponding to the control flow in @p Kernel. 2155 /// 2156 /// @param Kernel The kernel to print 2157 void printKernel(ppcg_kernel *Kernel) { 2158 auto *P = isl_printer_to_str(S->getIslCtx()); 2159 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2160 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2161 P = isl_ast_node_print(Kernel->tree, P, Options); 2162 char *String = isl_printer_get_str(P); 2163 printf("%s\n", String); 2164 free(String); 2165 isl_printer_free(P); 2166 } 2167 2168 /// Print C code corresponding to the GPU code described by @p Tree. 2169 /// 2170 /// @param Tree An AST describing GPU code 2171 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 2172 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 2173 auto *P = isl_printer_to_str(S->getIslCtx()); 2174 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2175 2176 PrintGPUUserData Data; 2177 Data.PPCGProg = PPCGProg; 2178 2179 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2180 Options = 2181 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 2182 P = isl_ast_node_print(Tree, P, Options); 2183 char *String = isl_printer_get_str(P); 2184 printf("# host\n"); 2185 printf("%s\n", String); 2186 free(String); 2187 isl_printer_free(P); 2188 2189 for (auto Kernel : Data.Kernels) { 2190 printf("# kernel%d\n", Kernel->id); 2191 printKernel(Kernel); 2192 } 2193 } 2194 2195 // Generate a GPU program using PPCG. 2196 // 2197 // GPU mapping consists of multiple steps: 2198 // 2199 // 1) Compute new schedule for the program. 2200 // 2) Map schedule to GPU (TODO) 2201 // 3) Generate code for new schedule (TODO) 2202 // 2203 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2204 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2205 // strategy directly from this pass. 2206 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2207 2208 auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2209 2210 PPCGGen->ctx = S->getIslCtx(); 2211 PPCGGen->options = PPCGScop->options; 2212 PPCGGen->print = nullptr; 2213 PPCGGen->print_user = nullptr; 2214 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2215 PPCGGen->prog = PPCGProg; 2216 PPCGGen->tree = nullptr; 2217 PPCGGen->types.n = 0; 2218 PPCGGen->types.name = nullptr; 2219 PPCGGen->sizes = nullptr; 2220 PPCGGen->used_sizes = nullptr; 2221 PPCGGen->kernel_id = 0; 2222 2223 // Set scheduling strategy to same strategy PPCG is using. 2224 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2225 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 2226 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2227 2228 isl_schedule *Schedule = get_schedule(PPCGGen); 2229 2230 int has_permutable = has_any_permutable_node(Schedule); 2231 2232 if (!has_permutable || has_permutable < 0) { 2233 Schedule = isl_schedule_free(Schedule); 2234 } else { 2235 Schedule = map_to_device(PPCGGen, Schedule); 2236 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 2237 } 2238 2239 if (DumpSchedule) { 2240 isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2241 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2242 P = isl_printer_print_str(P, "Schedule\n"); 2243 P = isl_printer_print_str(P, "========\n"); 2244 if (Schedule) 2245 P = isl_printer_print_schedule(P, Schedule); 2246 else 2247 P = isl_printer_print_str(P, "No schedule found\n"); 2248 2249 printf("%s\n", isl_printer_get_str(P)); 2250 isl_printer_free(P); 2251 } 2252 2253 if (DumpCode) { 2254 printf("Code\n"); 2255 printf("====\n"); 2256 if (PPCGGen->tree) 2257 printGPUTree(PPCGGen->tree, PPCGProg); 2258 else 2259 printf("No code generated\n"); 2260 } 2261 2262 isl_schedule_free(Schedule); 2263 2264 return PPCGGen; 2265 } 2266 2267 /// Free gpu_gen structure. 2268 /// 2269 /// @param PPCGGen The ppcg_gen object to free. 2270 void freePPCGGen(gpu_gen *PPCGGen) { 2271 isl_ast_node_free(PPCGGen->tree); 2272 isl_union_map_free(PPCGGen->sizes); 2273 isl_union_map_free(PPCGGen->used_sizes); 2274 free(PPCGGen); 2275 } 2276 2277 /// Free the options in the ppcg scop structure. 2278 /// 2279 /// ppcg is not freeing these options for us. To avoid leaks we do this 2280 /// ourselves. 2281 /// 2282 /// @param PPCGScop The scop referencing the options to free. 2283 void freeOptions(ppcg_scop *PPCGScop) { 2284 free(PPCGScop->options->debug); 2285 PPCGScop->options->debug = nullptr; 2286 free(PPCGScop->options); 2287 PPCGScop->options = nullptr; 2288 } 2289 2290 /// Approximate the number of points in the set. 2291 /// 2292 /// This function returns an ast expression that overapproximates the number 2293 /// of points in an isl set through the rectangular hull surrounding this set. 2294 /// 2295 /// @param Set The set to count. 2296 /// @param Build The isl ast build object to use for creating the ast 2297 /// expression. 2298 /// 2299 /// @returns An approximation of the number of points in the set. 2300 __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 2301 __isl_keep isl_ast_build *Build) { 2302 2303 isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 2304 auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 2305 2306 isl_space *Space = isl_set_get_space(Set); 2307 Space = isl_space_params(Space); 2308 auto *Univ = isl_set_universe(Space); 2309 isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 2310 2311 for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 2312 isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 2313 isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 2314 isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 2315 DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 2316 auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 2317 Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 2318 } 2319 2320 isl_set_free(Set); 2321 isl_pw_aff_free(OneAff); 2322 2323 return Expr; 2324 } 2325 2326 /// Approximate a number of dynamic instructions executed by a given 2327 /// statement. 2328 /// 2329 /// @param Stmt The statement for which to compute the number of dynamic 2330 /// instructions. 2331 /// @param Build The isl ast build object to use for creating the ast 2332 /// expression. 2333 /// @returns An approximation of the number of dynamic instructions executed 2334 /// by @p Stmt. 2335 __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 2336 __isl_keep isl_ast_build *Build) { 2337 auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 2338 2339 long InstCount = 0; 2340 2341 if (Stmt.isBlockStmt()) { 2342 auto *BB = Stmt.getBasicBlock(); 2343 InstCount = std::distance(BB->begin(), BB->end()); 2344 } else { 2345 auto *R = Stmt.getRegion(); 2346 2347 for (auto *BB : R->blocks()) { 2348 InstCount += std::distance(BB->begin(), BB->end()); 2349 } 2350 } 2351 2352 isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 2353 auto *InstExpr = isl_ast_expr_from_val(InstVal); 2354 return isl_ast_expr_mul(InstExpr, Iterations); 2355 } 2356 2357 /// Approximate dynamic instructions executed in scop. 2358 /// 2359 /// @param S The scop for which to approximate dynamic instructions. 2360 /// @param Build The isl ast build object to use for creating the ast 2361 /// expression. 2362 /// @returns An approximation of the number of dynamic instructions executed 2363 /// in @p S. 2364 __isl_give isl_ast_expr * 2365 getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 2366 isl_ast_expr *Instructions; 2367 2368 isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 2369 Instructions = isl_ast_expr_from_val(Zero); 2370 2371 for (ScopStmt &Stmt : S) { 2372 isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 2373 Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 2374 } 2375 return Instructions; 2376 } 2377 2378 /// Create a check that ensures sufficient compute in scop. 2379 /// 2380 /// @param S The scop for which to ensure sufficient compute. 2381 /// @param Build The isl ast build object to use for creating the ast 2382 /// expression. 2383 /// @returns An expression that evaluates to TRUE in case of sufficient 2384 /// compute and to FALSE, otherwise. 2385 __isl_give isl_ast_expr * 2386 createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 2387 auto Iterations = getNumberOfIterations(S, Build); 2388 auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 2389 auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 2390 return isl_ast_expr_ge(Iterations, MinComputeExpr); 2391 } 2392 2393 /// Generate code for a given GPU AST described by @p Root. 2394 /// 2395 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 2396 /// @param Prog The GPU Program to generate code for. 2397 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 2398 ScopAnnotator Annotator; 2399 Annotator.buildAliasScopes(*S); 2400 2401 Region *R = &S->getRegion(); 2402 2403 simplifyRegion(R, DT, LI, RI); 2404 2405 BasicBlock *EnteringBB = R->getEnteringBlock(); 2406 2407 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 2408 2409 // Only build the run-time condition and parameters _after_ having 2410 // introduced the conditional branch. This is important as the conditional 2411 // branch will guard the original scop from new induction variables that 2412 // the SCEVExpander may introduce while code generating the parameters and 2413 // which may introduce scalar dependences that prevent us from correctly 2414 // code generating this scop. 2415 BasicBlock *StartBlock = 2416 executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 2417 2418 GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 2419 StartBlock, Prog); 2420 2421 // TODO: Handle LICM 2422 auto SplitBlock = StartBlock->getSinglePredecessor(); 2423 Builder.SetInsertPoint(SplitBlock->getTerminator()); 2424 NodeBuilder.addParameters(S->getContext()); 2425 2426 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 2427 isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build); 2428 isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 2429 Condition = isl_ast_expr_and(Condition, SufficientCompute); 2430 isl_ast_build_free(Build); 2431 2432 Value *RTC = NodeBuilder.createRTC(Condition); 2433 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2434 2435 Builder.SetInsertPoint(&*StartBlock->begin()); 2436 2437 NodeBuilder.initializeAfterRTH(); 2438 NodeBuilder.create(Root); 2439 NodeBuilder.finalize(); 2440 2441 /// In case a sequential kernel has more surrounding loops as any parallel 2442 /// kernel, the SCoP is probably mostly sequential. Hence, there is no 2443 /// point in running it on a GPU. 2444 if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 2445 SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 2446 2447 if (!NodeBuilder.BuildSuccessful) 2448 SplitBlock->getTerminator()->setOperand(0, Builder.getFalse()); 2449 } 2450 2451 bool runOnScop(Scop &CurrentScop) override { 2452 S = &CurrentScop; 2453 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2454 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2455 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2456 DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 2457 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2458 2459 // We currently do not support scops with invariant loads. 2460 if (S->hasInvariantAccesses()) 2461 return false; 2462 2463 auto PPCGScop = createPPCGScop(); 2464 auto PPCGProg = createPPCGProg(PPCGScop); 2465 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 2466 2467 if (PPCGGen->tree) 2468 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 2469 2470 freeOptions(PPCGScop); 2471 freePPCGGen(PPCGGen); 2472 gpu_prog_free(PPCGProg); 2473 ppcg_scop_free(PPCGScop); 2474 2475 return true; 2476 } 2477 2478 void printScop(raw_ostream &, Scop &) const override {} 2479 2480 void getAnalysisUsage(AnalysisUsage &AU) const override { 2481 AU.addRequired<DominatorTreeWrapperPass>(); 2482 AU.addRequired<RegionInfoPass>(); 2483 AU.addRequired<ScalarEvolutionWrapperPass>(); 2484 AU.addRequired<ScopDetection>(); 2485 AU.addRequired<ScopInfoRegionPass>(); 2486 AU.addRequired<LoopInfoWrapperPass>(); 2487 2488 AU.addPreserved<AAResultsWrapperPass>(); 2489 AU.addPreserved<BasicAAWrapperPass>(); 2490 AU.addPreserved<LoopInfoWrapperPass>(); 2491 AU.addPreserved<DominatorTreeWrapperPass>(); 2492 AU.addPreserved<GlobalsAAWrapperPass>(); 2493 AU.addPreserved<ScopDetection>(); 2494 AU.addPreserved<ScalarEvolutionWrapperPass>(); 2495 AU.addPreserved<SCEVAAWrapperPass>(); 2496 2497 // FIXME: We do not yet add regions for the newly generated code to the 2498 // region tree. 2499 AU.addPreserved<RegionInfoPass>(); 2500 AU.addPreserved<ScopInfoRegionPass>(); 2501 } 2502 }; 2503 } // namespace 2504 2505 char PPCGCodeGeneration::ID = 1; 2506 2507 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); } 2508 2509 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 2510 "Polly - Apply PPCG translation to SCOP", false, false) 2511 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 2512 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 2513 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 2514 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 2515 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 2516 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 2517 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 2518 "Polly - Apply PPCG translation to SCOP", false, false) 2519