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