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