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 Args.push_back(Builder.getInt64Ty()); 1166 1167 for (auto *V : SubtreeValues) 1168 Args.push_back(V->getType()); 1169 1170 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1171 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1172 GPUModule.get()); 1173 FN->setCallingConv(CallingConv::PTX_Kernel); 1174 1175 auto Arg = FN->arg_begin(); 1176 for (long i = 0; i < Kernel->n_array; i++) { 1177 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1178 continue; 1179 1180 Arg->setName(Kernel->array[i].array->name); 1181 1182 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1183 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1184 Type *EleTy = SAI->getElementType(); 1185 Value *Val = &*Arg; 1186 SmallVector<const SCEV *, 4> Sizes; 1187 isl_ast_build *Build = 1188 isl_ast_build_from_context(isl_set_copy(Prog->context)); 1189 for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1190 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1191 Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j])); 1192 auto V = ExprBuilder.create(DimSize); 1193 Sizes.push_back(SE.getSCEV(V)); 1194 } 1195 const ScopArrayInfo *SAIRep = 1196 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array); 1197 LocalArrays.push_back(Val); 1198 1199 isl_ast_build_free(Build); 1200 KernelIds.push_back(Id); 1201 IDToSAI[Id] = SAIRep; 1202 Arg++; 1203 } 1204 1205 for (long i = 0; i < NumHostIters; i++) { 1206 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1207 Arg->setName(isl_id_get_name(Id)); 1208 IDToValue[Id] = &*Arg; 1209 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1210 Arg++; 1211 } 1212 1213 for (long i = 0; i < NumVars; i++) { 1214 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1215 Arg->setName(isl_id_get_name(Id)); 1216 IDToValue[Id] = &*Arg; 1217 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1218 Arg++; 1219 } 1220 1221 for (auto *V : SubtreeValues) { 1222 Arg->setName(V->getName()); 1223 ValueMap[V] = &*Arg; 1224 Arg++; 1225 } 1226 1227 return FN; 1228 } 1229 1230 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1231 Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x, 1232 Intrinsic::nvvm_read_ptx_sreg_ctaid_y}; 1233 1234 Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x, 1235 Intrinsic::nvvm_read_ptx_sreg_tid_y, 1236 Intrinsic::nvvm_read_ptx_sreg_tid_z}; 1237 1238 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1239 std::string Name = isl_id_get_name(Id); 1240 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1241 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1242 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1243 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1244 IDToValue[Id] = Val; 1245 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1246 }; 1247 1248 for (int i = 0; i < Kernel->n_grid; ++i) { 1249 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1250 addId(Id, IntrinsicsBID[i]); 1251 } 1252 1253 for (int i = 0; i < Kernel->n_block; ++i) { 1254 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1255 addId(Id, IntrinsicsTID[i]); 1256 } 1257 } 1258 1259 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 1260 auto Arg = FN->arg_begin(); 1261 for (long i = 0; i < Kernel->n_array; i++) { 1262 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1263 continue; 1264 1265 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1266 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1267 isl_id_free(Id); 1268 1269 if (SAI->getNumberOfDimensions() > 0) { 1270 Arg++; 1271 continue; 1272 } 1273 1274 Value *Alloca = BlockGen.getOrCreateScalarAlloca(SAI->getBasePtr()); 1275 Value *ArgPtr = &*Arg; 1276 Type *TypePtr = SAI->getElementType()->getPointerTo(); 1277 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 1278 Value *Val = Builder.CreateLoad(TypedArgPtr); 1279 Builder.CreateStore(Val, Alloca); 1280 1281 Arg++; 1282 } 1283 } 1284 1285 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1286 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1287 1288 for (int i = 0; i < Kernel->n_var; ++i) { 1289 struct ppcg_kernel_var &Var = Kernel->var[i]; 1290 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1291 Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1292 1293 Type *ArrayTy = EleTy; 1294 SmallVector<const SCEV *, 4> Sizes; 1295 1296 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1297 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1298 long Bound = isl_val_get_num_si(Val); 1299 isl_val_free(Val); 1300 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1301 } 1302 1303 for (int j = Var.array->n_index - 1; j >= 0; --j) { 1304 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1305 long Bound = isl_val_get_num_si(Val); 1306 isl_val_free(Val); 1307 ArrayTy = ArrayType::get(ArrayTy, Bound); 1308 } 1309 1310 const ScopArrayInfo *SAI; 1311 Value *Allocation; 1312 if (Var.type == ppcg_access_shared) { 1313 auto GlobalVar = new GlobalVariable( 1314 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1315 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1316 GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1317 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1318 1319 Allocation = GlobalVar; 1320 } else if (Var.type == ppcg_access_private) { 1321 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1322 } else { 1323 llvm_unreachable("unknown variable type"); 1324 } 1325 SAI = S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, 1326 ScopArrayInfo::MK_Array); 1327 Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1328 IDToValue[Id] = Allocation; 1329 LocalArrays.push_back(Allocation); 1330 KernelIds.push_back(Id); 1331 IDToSAI[Id] = SAI; 1332 } 1333 } 1334 1335 void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel, 1336 SetVector<Value *> &SubtreeValues) { 1337 1338 std::string Identifier = "kernel_" + std::to_string(Kernel->id); 1339 GPUModule.reset(new Module(Identifier, Builder.getContext())); 1340 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 1341 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 1342 1343 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 1344 1345 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 1346 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 1347 1348 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1349 DT.addNewBlock(EntryBlock, PrevBlock); 1350 1351 Builder.SetInsertPoint(EntryBlock); 1352 Builder.CreateRetVoid(); 1353 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 1354 1355 ScopDetection::markFunctionAsInvalid(FN); 1356 1357 prepareKernelArguments(Kernel, FN); 1358 createKernelVariables(Kernel, FN); 1359 insertKernelIntrinsics(Kernel); 1360 } 1361 1362 std::string GPUNodeBuilder::createKernelASM() { 1363 llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda")); 1364 std::string ErrMsg; 1365 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 1366 1367 if (!GPUTarget) { 1368 errs() << ErrMsg << "\n"; 1369 return ""; 1370 } 1371 1372 TargetOptions Options; 1373 Options.UnsafeFPMath = FastMath; 1374 std::unique_ptr<TargetMachine> TargetM( 1375 GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "", 1376 Options, Optional<Reloc::Model>())); 1377 1378 SmallString<0> ASMString; 1379 raw_svector_ostream ASMStream(ASMString); 1380 llvm::legacy::PassManager PM; 1381 1382 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 1383 1384 if (TargetM->addPassesToEmitFile( 1385 PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 1386 errs() << "The target does not support generation of this file type!\n"; 1387 return ""; 1388 } 1389 1390 PM.run(*GPUModule); 1391 1392 return ASMStream.str(); 1393 } 1394 1395 std::string GPUNodeBuilder::finalizeKernelFunction() { 1396 // Verify module. 1397 llvm::legacy::PassManager Passes; 1398 Passes.add(createVerifierPass()); 1399 Passes.run(*GPUModule); 1400 1401 if (DumpKernelIR) 1402 outs() << *GPUModule << "\n"; 1403 1404 // Optimize module. 1405 llvm::legacy::PassManager OptPasses; 1406 PassManagerBuilder PassBuilder; 1407 PassBuilder.OptLevel = 3; 1408 PassBuilder.SizeLevel = 0; 1409 PassBuilder.populateModulePassManager(OptPasses); 1410 OptPasses.run(*GPUModule); 1411 1412 std::string Assembly = createKernelASM(); 1413 1414 if (DumpKernelASM) 1415 outs() << Assembly << "\n"; 1416 1417 GPUModule.release(); 1418 KernelIDs.clear(); 1419 1420 return Assembly; 1421 } 1422 1423 namespace { 1424 class PPCGCodeGeneration : public ScopPass { 1425 public: 1426 static char ID; 1427 1428 /// The scop that is currently processed. 1429 Scop *S; 1430 1431 LoopInfo *LI; 1432 DominatorTree *DT; 1433 ScalarEvolution *SE; 1434 const DataLayout *DL; 1435 RegionInfo *RI; 1436 1437 PPCGCodeGeneration() : ScopPass(ID) {} 1438 1439 /// Construct compilation options for PPCG. 1440 /// 1441 /// @returns The compilation options. 1442 ppcg_options *createPPCGOptions() { 1443 auto DebugOptions = 1444 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 1445 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 1446 1447 DebugOptions->dump_schedule_constraints = false; 1448 DebugOptions->dump_schedule = false; 1449 DebugOptions->dump_final_schedule = false; 1450 DebugOptions->dump_sizes = false; 1451 DebugOptions->verbose = false; 1452 1453 Options->debug = DebugOptions; 1454 1455 Options->reschedule = true; 1456 Options->scale_tile_loops = false; 1457 Options->wrap = false; 1458 1459 Options->non_negative_parameters = false; 1460 Options->ctx = nullptr; 1461 Options->sizes = nullptr; 1462 1463 Options->tile_size = 32; 1464 1465 Options->use_private_memory = PrivateMemory; 1466 Options->use_shared_memory = SharedMemory; 1467 Options->max_shared_memory = 48 * 1024; 1468 1469 Options->target = PPCG_TARGET_CUDA; 1470 Options->openmp = false; 1471 Options->linearize_device_arrays = true; 1472 Options->live_range_reordering = false; 1473 1474 Options->opencl_compiler_options = nullptr; 1475 Options->opencl_use_gpu = false; 1476 Options->opencl_n_include_file = 0; 1477 Options->opencl_include_files = nullptr; 1478 Options->opencl_print_kernel_types = false; 1479 Options->opencl_embed_kernel_code = false; 1480 1481 Options->save_schedule_file = nullptr; 1482 Options->load_schedule_file = nullptr; 1483 1484 return Options; 1485 } 1486 1487 /// Get a tagged access relation containing all accesses of type @p AccessTy. 1488 /// 1489 /// Instead of a normal access of the form: 1490 /// 1491 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 1492 /// 1493 /// a tagged access has the form 1494 /// 1495 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 1496 /// 1497 /// where 'id' is an additional space that references the memory access that 1498 /// triggered the access. 1499 /// 1500 /// @param AccessTy The type of the memory accesses to collect. 1501 /// 1502 /// @return The relation describing all tagged memory accesses. 1503 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 1504 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 1505 1506 for (auto &Stmt : *S) 1507 for (auto &Acc : Stmt) 1508 if (Acc->getType() == AccessTy) { 1509 isl_map *Relation = Acc->getAccessRelation(); 1510 Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 1511 1512 isl_space *Space = isl_map_get_space(Relation); 1513 Space = isl_space_range(Space); 1514 Space = isl_space_from_range(Space); 1515 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 1516 isl_map *Universe = isl_map_universe(Space); 1517 Relation = isl_map_domain_product(Relation, Universe); 1518 Accesses = isl_union_map_add_map(Accesses, Relation); 1519 } 1520 1521 return Accesses; 1522 } 1523 1524 /// Get the set of all read accesses, tagged with the access id. 1525 /// 1526 /// @see getTaggedAccesses 1527 isl_union_map *getTaggedReads() { 1528 return getTaggedAccesses(MemoryAccess::READ); 1529 } 1530 1531 /// Get the set of all may (and must) accesses, tagged with the access id. 1532 /// 1533 /// @see getTaggedAccesses 1534 isl_union_map *getTaggedMayWrites() { 1535 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 1536 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 1537 } 1538 1539 /// Get the set of all must accesses, tagged with the access id. 1540 /// 1541 /// @see getTaggedAccesses 1542 isl_union_map *getTaggedMustWrites() { 1543 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 1544 } 1545 1546 /// Collect parameter and array names as isl_ids. 1547 /// 1548 /// To reason about the different parameters and arrays used, ppcg requires 1549 /// a list of all isl_ids in use. As PPCG traditionally performs 1550 /// source-to-source compilation each of these isl_ids is mapped to the 1551 /// expression that represents it. As we do not have a corresponding 1552 /// expression in Polly, we just map each id to a 'zero' expression to match 1553 /// the data format that ppcg expects. 1554 /// 1555 /// @returns Retun a map from collected ids to 'zero' ast expressions. 1556 __isl_give isl_id_to_ast_expr *getNames() { 1557 auto *Names = isl_id_to_ast_expr_alloc( 1558 S->getIslCtx(), 1559 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 1560 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 1561 auto *Space = S->getParamSpace(); 1562 1563 for (int I = 0, E = S->getNumParams(); I < E; ++I) { 1564 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 1565 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1566 } 1567 1568 for (auto &Array : S->arrays()) { 1569 auto Id = Array->getBasePtrId(); 1570 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 1571 } 1572 1573 isl_space_free(Space); 1574 isl_ast_expr_free(Zero); 1575 1576 return Names; 1577 } 1578 1579 /// Create a new PPCG scop from the current scop. 1580 /// 1581 /// The PPCG scop is initialized with data from the current polly::Scop. From 1582 /// this initial data, the data-dependences in the PPCG scop are initialized. 1583 /// We do not use Polly's dependence analysis for now, to ensure we match 1584 /// the PPCG default behaviour more closely. 1585 /// 1586 /// @returns A new ppcg scop. 1587 ppcg_scop *createPPCGScop() { 1588 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 1589 1590 PPCGScop->options = createPPCGOptions(); 1591 1592 PPCGScop->start = 0; 1593 PPCGScop->end = 0; 1594 1595 PPCGScop->context = S->getContext(); 1596 PPCGScop->domain = S->getDomains(); 1597 PPCGScop->call = nullptr; 1598 PPCGScop->tagged_reads = getTaggedReads(); 1599 PPCGScop->reads = S->getReads(); 1600 PPCGScop->live_in = nullptr; 1601 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 1602 PPCGScop->may_writes = S->getWrites(); 1603 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 1604 PPCGScop->must_writes = S->getMustWrites(); 1605 PPCGScop->live_out = nullptr; 1606 PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace()); 1607 PPCGScop->tagger = nullptr; 1608 1609 PPCGScop->independence = nullptr; 1610 PPCGScop->dep_flow = nullptr; 1611 PPCGScop->tagged_dep_flow = nullptr; 1612 PPCGScop->dep_false = nullptr; 1613 PPCGScop->dep_forced = nullptr; 1614 PPCGScop->dep_order = nullptr; 1615 PPCGScop->tagged_dep_order = nullptr; 1616 1617 PPCGScop->schedule = S->getScheduleTree(); 1618 PPCGScop->names = getNames(); 1619 1620 PPCGScop->pet = nullptr; 1621 1622 compute_tagger(PPCGScop); 1623 compute_dependences(PPCGScop); 1624 1625 return PPCGScop; 1626 } 1627 1628 /// Collect the array acesses in a statement. 1629 /// 1630 /// @param Stmt The statement for which to collect the accesses. 1631 /// 1632 /// @returns A list of array accesses. 1633 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 1634 gpu_stmt_access *Accesses = nullptr; 1635 1636 for (MemoryAccess *Acc : Stmt) { 1637 auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 1638 Access->read = Acc->isRead(); 1639 Access->write = Acc->isWrite(); 1640 Access->access = Acc->getAccessRelation(); 1641 isl_space *Space = isl_map_get_space(Access->access); 1642 Space = isl_space_range(Space); 1643 Space = isl_space_from_range(Space); 1644 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 1645 isl_map *Universe = isl_map_universe(Space); 1646 Access->tagged_access = 1647 isl_map_domain_product(Acc->getAccessRelation(), Universe); 1648 Access->exact_write = !Acc->isMayWrite(); 1649 Access->ref_id = Acc->getId(); 1650 Access->next = Accesses; 1651 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 1652 Accesses = Access; 1653 } 1654 1655 return Accesses; 1656 } 1657 1658 /// Collect the list of GPU statements. 1659 /// 1660 /// Each statement has an id, a pointer to the underlying data structure, 1661 /// as well as a list with all memory accesses. 1662 /// 1663 /// TODO: Initialize the list of memory accesses. 1664 /// 1665 /// @returns A linked-list of statements. 1666 gpu_stmt *getStatements() { 1667 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 1668 std::distance(S->begin(), S->end())); 1669 1670 int i = 0; 1671 for (auto &Stmt : *S) { 1672 gpu_stmt *GPUStmt = &Stmts[i]; 1673 1674 GPUStmt->id = Stmt.getDomainId(); 1675 1676 // We use the pet stmt pointer to keep track of the Polly statements. 1677 GPUStmt->stmt = (pet_stmt *)&Stmt; 1678 GPUStmt->accesses = getStmtAccesses(Stmt); 1679 i++; 1680 } 1681 1682 return Stmts; 1683 } 1684 1685 /// Derive the extent of an array. 1686 /// 1687 /// The extent of an array is defined by the set of memory locations for 1688 /// which a memory access in the iteration domain exists. 1689 /// 1690 /// @param Array The array to derive the extent for. 1691 /// 1692 /// @returns An isl_set describing the extent of the array. 1693 __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 1694 isl_union_map *Accesses = S->getAccesses(); 1695 Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 1696 isl_union_set *AccessUSet = isl_union_map_range(Accesses); 1697 isl_set *AccessSet = 1698 isl_union_set_extract_set(AccessUSet, Array->getSpace()); 1699 isl_union_set_free(AccessUSet); 1700 1701 return AccessSet; 1702 } 1703 1704 /// Derive the bounds of an array. 1705 /// 1706 /// For the first dimension we derive the bound of the array from the extent 1707 /// of this dimension. For inner dimensions we obtain their size directly from 1708 /// ScopArrayInfo. 1709 /// 1710 /// @param PPCGArray The array to compute bounds for. 1711 /// @param Array The polly array from which to take the information. 1712 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 1713 if (PPCGArray.n_index > 0) { 1714 isl_set *Dom = isl_set_copy(PPCGArray.extent); 1715 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 1716 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 1717 isl_set_free(Dom); 1718 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 1719 isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom)); 1720 isl_aff *One = isl_aff_zero_on_domain(LS); 1721 One = isl_aff_add_constant_si(One, 1); 1722 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 1723 Bound = isl_pw_aff_gist(Bound, S->getContext()); 1724 PPCGArray.bound[0] = Bound; 1725 } 1726 1727 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 1728 isl_pw_aff *Bound = Array->getDimensionSizePw(i); 1729 auto LS = isl_pw_aff_get_domain_space(Bound); 1730 auto Aff = isl_multi_aff_zero(LS); 1731 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 1732 PPCGArray.bound[i] = Bound; 1733 } 1734 } 1735 1736 /// Create the arrays for @p PPCGProg. 1737 /// 1738 /// @param PPCGProg The program to compute the arrays for. 1739 void createArrays(gpu_prog *PPCGProg) { 1740 int i = 0; 1741 for (auto &Array : S->arrays()) { 1742 std::string TypeName; 1743 raw_string_ostream OS(TypeName); 1744 1745 OS << *Array->getElementType(); 1746 TypeName = OS.str(); 1747 1748 gpu_array_info &PPCGArray = PPCGProg->array[i]; 1749 1750 PPCGArray.space = Array->getSpace(); 1751 PPCGArray.type = strdup(TypeName.c_str()); 1752 PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 1753 PPCGArray.name = strdup(Array->getName().c_str()); 1754 PPCGArray.extent = nullptr; 1755 PPCGArray.n_index = Array->getNumberOfDimensions(); 1756 PPCGArray.bound = 1757 isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index); 1758 PPCGArray.extent = getExtent(Array); 1759 PPCGArray.n_ref = 0; 1760 PPCGArray.refs = nullptr; 1761 PPCGArray.accessed = true; 1762 PPCGArray.read_only_scalar = false; 1763 PPCGArray.has_compound_element = false; 1764 PPCGArray.local = false; 1765 PPCGArray.declare_local = false; 1766 PPCGArray.global = false; 1767 PPCGArray.linearize = false; 1768 PPCGArray.dep_order = nullptr; 1769 PPCGArray.user = Array; 1770 1771 setArrayBounds(PPCGArray, Array); 1772 i++; 1773 1774 collect_references(PPCGProg, &PPCGArray); 1775 } 1776 } 1777 1778 /// Create an identity map between the arrays in the scop. 1779 /// 1780 /// @returns An identity map between the arrays in the scop. 1781 isl_union_map *getArrayIdentity() { 1782 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 1783 1784 for (auto &Array : S->arrays()) { 1785 isl_space *Space = Array->getSpace(); 1786 Space = isl_space_map_from_set(Space); 1787 isl_map *Identity = isl_map_identity(Space); 1788 Maps = isl_union_map_add_map(Maps, Identity); 1789 } 1790 1791 return Maps; 1792 } 1793 1794 /// Create a default-initialized PPCG GPU program. 1795 /// 1796 /// @returns A new gpu grogram description. 1797 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 1798 1799 if (!PPCGScop) 1800 return nullptr; 1801 1802 auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 1803 1804 PPCGProg->ctx = S->getIslCtx(); 1805 PPCGProg->scop = PPCGScop; 1806 PPCGProg->context = isl_set_copy(PPCGScop->context); 1807 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 1808 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 1809 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 1810 PPCGProg->tagged_must_kill = 1811 isl_union_map_copy(PPCGScop->tagged_must_kills); 1812 PPCGProg->to_inner = getArrayIdentity(); 1813 PPCGProg->to_outer = getArrayIdentity(); 1814 PPCGProg->may_persist = compute_may_persist(PPCGProg); 1815 PPCGProg->any_to_outer = nullptr; 1816 PPCGProg->array_order = nullptr; 1817 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 1818 PPCGProg->stmts = getStatements(); 1819 PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 1820 PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 1821 PPCGProg->n_array); 1822 1823 createArrays(PPCGProg); 1824 1825 return PPCGProg; 1826 } 1827 1828 struct PrintGPUUserData { 1829 struct cuda_info *CudaInfo; 1830 struct gpu_prog *PPCGProg; 1831 std::vector<ppcg_kernel *> Kernels; 1832 }; 1833 1834 /// Print a user statement node in the host code. 1835 /// 1836 /// We use ppcg's printing facilities to print the actual statement and 1837 /// additionally build up a list of all kernels that are encountered in the 1838 /// host ast. 1839 /// 1840 /// @param P The printer to print to 1841 /// @param Options The printing options to use 1842 /// @param Node The node to print 1843 /// @param User A user pointer to carry additional data. This pointer is 1844 /// expected to be of type PrintGPUUserData. 1845 /// 1846 /// @returns A printer to which the output has been printed. 1847 static __isl_give isl_printer * 1848 printHostUser(__isl_take isl_printer *P, 1849 __isl_take isl_ast_print_options *Options, 1850 __isl_take isl_ast_node *Node, void *User) { 1851 auto Data = (struct PrintGPUUserData *)User; 1852 auto Id = isl_ast_node_get_annotation(Node); 1853 1854 if (Id) { 1855 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 1856 1857 // If this is a user statement, format it ourselves as ppcg would 1858 // otherwise try to call pet functionality that is not available in 1859 // Polly. 1860 if (IsUser) { 1861 P = isl_printer_start_line(P); 1862 P = isl_printer_print_ast_node(P, Node); 1863 P = isl_printer_end_line(P); 1864 isl_id_free(Id); 1865 isl_ast_print_options_free(Options); 1866 return P; 1867 } 1868 1869 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 1870 isl_id_free(Id); 1871 Data->Kernels.push_back(Kernel); 1872 } 1873 1874 return print_host_user(P, Options, Node, User); 1875 } 1876 1877 /// Print C code corresponding to the control flow in @p Kernel. 1878 /// 1879 /// @param Kernel The kernel to print 1880 void printKernel(ppcg_kernel *Kernel) { 1881 auto *P = isl_printer_to_str(S->getIslCtx()); 1882 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 1883 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 1884 P = isl_ast_node_print(Kernel->tree, P, Options); 1885 char *String = isl_printer_get_str(P); 1886 printf("%s\n", String); 1887 free(String); 1888 isl_printer_free(P); 1889 } 1890 1891 /// Print C code corresponding to the GPU code described by @p Tree. 1892 /// 1893 /// @param Tree An AST describing GPU code 1894 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 1895 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 1896 auto *P = isl_printer_to_str(S->getIslCtx()); 1897 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 1898 1899 PrintGPUUserData Data; 1900 Data.PPCGProg = PPCGProg; 1901 1902 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 1903 Options = 1904 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 1905 P = isl_ast_node_print(Tree, P, Options); 1906 char *String = isl_printer_get_str(P); 1907 printf("# host\n"); 1908 printf("%s\n", String); 1909 free(String); 1910 isl_printer_free(P); 1911 1912 for (auto Kernel : Data.Kernels) { 1913 printf("# kernel%d\n", Kernel->id); 1914 printKernel(Kernel); 1915 } 1916 } 1917 1918 // Generate a GPU program using PPCG. 1919 // 1920 // GPU mapping consists of multiple steps: 1921 // 1922 // 1) Compute new schedule for the program. 1923 // 2) Map schedule to GPU (TODO) 1924 // 3) Generate code for new schedule (TODO) 1925 // 1926 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 1927 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 1928 // strategy directly from this pass. 1929 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 1930 1931 auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 1932 1933 PPCGGen->ctx = S->getIslCtx(); 1934 PPCGGen->options = PPCGScop->options; 1935 PPCGGen->print = nullptr; 1936 PPCGGen->print_user = nullptr; 1937 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 1938 PPCGGen->prog = PPCGProg; 1939 PPCGGen->tree = nullptr; 1940 PPCGGen->types.n = 0; 1941 PPCGGen->types.name = nullptr; 1942 PPCGGen->sizes = nullptr; 1943 PPCGGen->used_sizes = nullptr; 1944 PPCGGen->kernel_id = 0; 1945 1946 // Set scheduling strategy to same strategy PPCG is using. 1947 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 1948 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 1949 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 1950 1951 isl_schedule *Schedule = get_schedule(PPCGGen); 1952 1953 int has_permutable = has_any_permutable_node(Schedule); 1954 1955 if (!has_permutable || has_permutable < 0) { 1956 Schedule = isl_schedule_free(Schedule); 1957 } else { 1958 Schedule = map_to_device(PPCGGen, Schedule); 1959 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 1960 } 1961 1962 if (DumpSchedule) { 1963 isl_printer *P = isl_printer_to_str(S->getIslCtx()); 1964 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 1965 P = isl_printer_print_str(P, "Schedule\n"); 1966 P = isl_printer_print_str(P, "========\n"); 1967 if (Schedule) 1968 P = isl_printer_print_schedule(P, Schedule); 1969 else 1970 P = isl_printer_print_str(P, "No schedule found\n"); 1971 1972 printf("%s\n", isl_printer_get_str(P)); 1973 isl_printer_free(P); 1974 } 1975 1976 if (DumpCode) { 1977 printf("Code\n"); 1978 printf("====\n"); 1979 if (PPCGGen->tree) 1980 printGPUTree(PPCGGen->tree, PPCGProg); 1981 else 1982 printf("No code generated\n"); 1983 } 1984 1985 isl_schedule_free(Schedule); 1986 1987 return PPCGGen; 1988 } 1989 1990 /// Free gpu_gen structure. 1991 /// 1992 /// @param PPCGGen The ppcg_gen object to free. 1993 void freePPCGGen(gpu_gen *PPCGGen) { 1994 isl_ast_node_free(PPCGGen->tree); 1995 isl_union_map_free(PPCGGen->sizes); 1996 isl_union_map_free(PPCGGen->used_sizes); 1997 free(PPCGGen); 1998 } 1999 2000 /// Free the options in the ppcg scop structure. 2001 /// 2002 /// ppcg is not freeing these options for us. To avoid leaks we do this 2003 /// ourselves. 2004 /// 2005 /// @param PPCGScop The scop referencing the options to free. 2006 void freeOptions(ppcg_scop *PPCGScop) { 2007 free(PPCGScop->options->debug); 2008 PPCGScop->options->debug = nullptr; 2009 free(PPCGScop->options); 2010 PPCGScop->options = nullptr; 2011 } 2012 2013 /// Generate code for a given GPU AST described by @p Root. 2014 /// 2015 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 2016 /// @param Prog The GPU Program to generate code for. 2017 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 2018 ScopAnnotator Annotator; 2019 Annotator.buildAliasScopes(*S); 2020 2021 Region *R = &S->getRegion(); 2022 2023 simplifyRegion(R, DT, LI, RI); 2024 2025 BasicBlock *EnteringBB = R->getEnteringBlock(); 2026 2027 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 2028 2029 GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S, 2030 Prog); 2031 2032 // Only build the run-time condition and parameters _after_ having 2033 // introduced the conditional branch. This is important as the conditional 2034 // branch will guard the original scop from new induction variables that 2035 // the SCEVExpander may introduce while code generating the parameters and 2036 // which may introduce scalar dependences that prevent us from correctly 2037 // code generating this scop. 2038 BasicBlock *StartBlock = 2039 executeScopConditionally(*S, this, Builder.getTrue()); 2040 2041 // TODO: Handle LICM 2042 auto SplitBlock = StartBlock->getSinglePredecessor(); 2043 Builder.SetInsertPoint(SplitBlock->getTerminator()); 2044 NodeBuilder.addParameters(S->getContext()); 2045 2046 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 2047 isl_ast_expr *Condition = IslAst::buildRunCondition(S, Build); 2048 isl_ast_build_free(Build); 2049 2050 Value *RTC = NodeBuilder.createRTC(Condition); 2051 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 2052 2053 Builder.SetInsertPoint(&*StartBlock->begin()); 2054 2055 NodeBuilder.initializeAfterRTH(); 2056 NodeBuilder.create(Root); 2057 NodeBuilder.finalize(); 2058 } 2059 2060 bool runOnScop(Scop &CurrentScop) override { 2061 S = &CurrentScop; 2062 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2063 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2064 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2065 DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout(); 2066 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 2067 2068 // We currently do not support scops with invariant loads. 2069 if (S->hasInvariantAccesses()) 2070 return false; 2071 2072 auto PPCGScop = createPPCGScop(); 2073 auto PPCGProg = createPPCGProg(PPCGScop); 2074 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 2075 2076 if (PPCGGen->tree) 2077 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 2078 2079 freeOptions(PPCGScop); 2080 freePPCGGen(PPCGGen); 2081 gpu_prog_free(PPCGProg); 2082 ppcg_scop_free(PPCGScop); 2083 2084 return true; 2085 } 2086 2087 void printScop(raw_ostream &, Scop &) const override {} 2088 2089 void getAnalysisUsage(AnalysisUsage &AU) const override { 2090 AU.addRequired<DominatorTreeWrapperPass>(); 2091 AU.addRequired<RegionInfoPass>(); 2092 AU.addRequired<ScalarEvolutionWrapperPass>(); 2093 AU.addRequired<ScopDetection>(); 2094 AU.addRequired<ScopInfoRegionPass>(); 2095 AU.addRequired<LoopInfoWrapperPass>(); 2096 2097 AU.addPreserved<AAResultsWrapperPass>(); 2098 AU.addPreserved<BasicAAWrapperPass>(); 2099 AU.addPreserved<LoopInfoWrapperPass>(); 2100 AU.addPreserved<DominatorTreeWrapperPass>(); 2101 AU.addPreserved<GlobalsAAWrapperPass>(); 2102 AU.addPreserved<PostDominatorTreeWrapperPass>(); 2103 AU.addPreserved<ScopDetection>(); 2104 AU.addPreserved<ScalarEvolutionWrapperPass>(); 2105 AU.addPreserved<SCEVAAWrapperPass>(); 2106 2107 // FIXME: We do not yet add regions for the newly generated code to the 2108 // region tree. 2109 AU.addPreserved<RegionInfoPass>(); 2110 AU.addPreserved<ScopInfoRegionPass>(); 2111 } 2112 }; 2113 } 2114 2115 char PPCGCodeGeneration::ID = 1; 2116 2117 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); } 2118 2119 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 2120 "Polly - Apply PPCG translation to SCOP", false, false) 2121 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 2122 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 2123 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 2124 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 2125 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 2126 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 2127 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 2128 "Polly - Apply PPCG translation to SCOP", false, false) 2129