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