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