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/PPCGCodeGeneration.h" 16 #include "polly/CodeGen/IslAst.h" 17 #include "polly/CodeGen/IslNodeBuilder.h" 18 #include "polly/CodeGen/Utils.h" 19 #include "polly/DependenceInfo.h" 20 #include "polly/LinkAllPasses.h" 21 #include "polly/Options.h" 22 #include "polly/ScopDetection.h" 23 #include "polly/ScopInfo.h" 24 #include "polly/Support/SCEVValidator.h" 25 #include "llvm/ADT/PostOrderIterator.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BasicAliasAnalysis.h" 28 #include "llvm/Analysis/GlobalsModRef.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<bool> ManagedMemory("polly-acc-codegen-managed-memory", 91 cl::desc("Generate Host kernel code assuming" 92 " that all memory has been" 93 " declared as managed memory"), 94 cl::Hidden, cl::init(false), cl::ZeroOrMore, 95 cl::cat(PollyCategory)); 96 97 static cl::opt<bool> 98 FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure", 99 cl::desc("Fail and generate a backtrace if" 100 " verifyModule fails on the GPU " 101 " kernel module."), 102 cl::Hidden, cl::init(false), cl::ZeroOrMore, 103 cl::cat(PollyCategory)); 104 105 static cl::opt<std::string> 106 CudaVersion("polly-acc-cuda-version", 107 cl::desc("The CUDA version to compile for"), cl::Hidden, 108 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory)); 109 110 static cl::opt<int> 111 MinCompute("polly-acc-mincompute", 112 cl::desc("Minimal number of compute statements to run on GPU."), 113 cl::Hidden, cl::init(10 * 512 * 512)); 114 115 /// Used to store information PPCG wants for kills. This information is 116 /// used by live range reordering. 117 /// 118 /// @see computeLiveRangeReordering 119 /// @see GPUNodeBuilder::createPPCGScop 120 /// @see GPUNodeBuilder::createPPCGProg 121 struct MustKillsInfo { 122 /// Collection of all kill statements that will be sequenced at the end of 123 /// PPCGScop->schedule. 124 /// 125 /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set` 126 /// which merges schedules in *arbitrary* order. 127 /// (we don't care about the order of the kills anyway). 128 isl::schedule KillsSchedule; 129 /// Map from kill statement instances to scalars that need to be 130 /// killed. 131 /// 132 /// We currently derive kill information for: 133 /// 1. phi nodes. PHI nodes are not alive outside the scop and can 134 /// consequently all be killed. 135 /// 2. Scalar arrays that are not used outside the Scop. This is 136 /// checked by `isScalarUsesContainedInScop`. 137 /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 138 isl::union_map TaggedMustKills; 139 140 /// Tagged must kills stripped of the tags. 141 /// [params] -> { Stmt_phantom[] -> scalar_to_kill[] } 142 isl::union_map MustKills; 143 144 MustKillsInfo() : KillsSchedule(nullptr) {} 145 }; 146 147 /// Check if SAI's uses are entirely contained within Scop S. 148 /// If a scalar is used only with a Scop, we are free to kill it, as no data 149 /// can flow in/out of the value any more. 150 /// @see computeMustKillsInfo 151 static bool isScalarUsesContainedInScop(const Scop &S, 152 const ScopArrayInfo *SAI) { 153 assert(SAI->isValueKind() && "this function only deals with scalars." 154 " Dealing with arrays required alias analysis"); 155 156 const Region &R = S.getRegion(); 157 for (User *U : SAI->getBasePtr()->users()) { 158 Instruction *I = dyn_cast<Instruction>(U); 159 assert(I && "invalid user of scop array info"); 160 if (!R.contains(I)) 161 return false; 162 } 163 return true; 164 } 165 166 /// Compute must-kills needed to enable live range reordering with PPCG. 167 /// 168 /// @params S The Scop to compute live range reordering information 169 /// @returns live range reordering information that can be used to setup 170 /// PPCG. 171 static MustKillsInfo computeMustKillsInfo(const Scop &S) { 172 const isl::space ParamSpace(isl::manage(S.getParamSpace())); 173 MustKillsInfo Info; 174 175 // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria: 176 // 1.1 phi nodes in scop. 177 // 1.2 scalars that are only used within the scop 178 SmallVector<isl::id, 4> KillMemIds; 179 for (ScopArrayInfo *SAI : S.arrays()) { 180 if (SAI->isPHIKind() || 181 (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI))) 182 KillMemIds.push_back(isl::manage(SAI->getBasePtrId())); 183 } 184 185 Info.TaggedMustKills = isl::union_map::empty(isl::space(ParamSpace)); 186 Info.MustKills = isl::union_map::empty(isl::space(ParamSpace)); 187 188 // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the 189 // schedule: 190 // - filter: "[control] -> { }" 191 // So, we choose to not create this to keep the output a little nicer, 192 // at the cost of some code complexity. 193 Info.KillsSchedule = nullptr; 194 195 for (isl::id &ToKillId : KillMemIds) { 196 isl::id KillStmtId = isl::id::alloc( 197 S.getIslCtx(), 198 std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr); 199 200 // NOTE: construction of tagged_must_kill: 201 // 2. We need to construct a map: 202 // [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] } 203 // To construct this, we use `isl_map_domain_product` on 2 maps`: 204 // 2a. StmtToScalar: 205 // [param] -> { Stmt_phantom[] -> scalar_to_kill[] } 206 // 2b. PhantomRefToScalar: 207 // [param] -> { ref_phantom[] -> scalar_to_kill[] } 208 // 209 // Combining these with `isl_map_domain_product` gives us 210 // TaggedMustKill: 211 // [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 212 213 // 2a. [param] -> { Stmt[] -> scalar_to_kill[] } 214 isl::map StmtToScalar = isl::map::universe(isl::space(ParamSpace)); 215 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId)); 216 StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId)); 217 218 isl::id PhantomRefId = isl::id::alloc( 219 S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(), 220 nullptr); 221 222 // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] } 223 isl::map PhantomRefToScalar = isl::map::universe(isl::space(ParamSpace)); 224 PhantomRefToScalar = 225 PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId); 226 PhantomRefToScalar = 227 PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId); 228 229 // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] } 230 isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar); 231 Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill); 232 233 // 2. [param] -> { Stmt[] -> scalar_to_kill[] } 234 Info.MustKills = Info.TaggedMustKills.domain_factor_domain(); 235 236 // 3. Create the kill schedule of the form: 237 // "[param] -> { Stmt_phantom[] }" 238 // Then add this to Info.KillsSchedule. 239 isl::space KillStmtSpace = ParamSpace; 240 KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId); 241 isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace); 242 243 isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain); 244 if (Info.KillsSchedule) 245 Info.KillsSchedule = Info.KillsSchedule.set(KillSchedule); 246 else 247 Info.KillsSchedule = KillSchedule; 248 } 249 250 return Info; 251 } 252 253 /// Create the ast expressions for a ScopStmt. 254 /// 255 /// This function is a callback for to generate the ast expressions for each 256 /// of the scheduled ScopStmts. 257 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt( 258 void *StmtT, isl_ast_build *Build, 259 isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA, 260 isl_id *Id, void *User), 261 void *UserIndex, 262 isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User), 263 void *UserExpr) { 264 265 ScopStmt *Stmt = (ScopStmt *)StmtT; 266 267 isl_ctx *Ctx; 268 269 if (!Stmt || !Build) 270 return NULL; 271 272 Ctx = isl_ast_build_get_ctx(Build); 273 isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0); 274 275 for (MemoryAccess *Acc : *Stmt) { 276 isl_map *AddrFunc = Acc->getAddressFunction(); 277 AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain()); 278 isl_id *RefId = Acc->getId(); 279 isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc); 280 isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA); 281 MPA = isl_multi_pw_aff_coalesce(MPA); 282 MPA = FunctionIndex(MPA, RefId, UserIndex); 283 isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA); 284 Access = FunctionExpr(Access, RefId, UserExpr); 285 RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access); 286 } 287 288 return RefToExpr; 289 } 290 291 /// Given a LLVM Type, compute its size in bytes, 292 static int computeSizeInBytes(const Type *T) { 293 int bytes = T->getPrimitiveSizeInBits() / 8; 294 if (bytes == 0) 295 bytes = T->getScalarSizeInBits() / 8; 296 return bytes; 297 } 298 299 /// Generate code for a GPU specific isl AST. 300 /// 301 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which 302 /// generates code for general-purpose AST nodes, with special functionality 303 /// for generating GPU specific user nodes. 304 /// 305 /// @see GPUNodeBuilder::createUser 306 class GPUNodeBuilder : public IslNodeBuilder { 307 public: 308 GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, 309 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE, 310 DominatorTree &DT, Scop &S, BasicBlock *StartBlock, 311 gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch) 312 : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock), 313 Prog(Prog), Runtime(Runtime), Arch(Arch) { 314 getExprBuilder().setIDToSAI(&IDToSAI); 315 } 316 317 /// Create after-run-time-check initialization code. 318 void initializeAfterRTH(); 319 320 /// Finalize the generated scop. 321 virtual void finalize(); 322 323 /// Track if the full build process was successful. 324 /// 325 /// This value is set to false, if throughout the build process an error 326 /// occurred which prevents us from generating valid GPU code. 327 bool BuildSuccessful = true; 328 329 /// The maximal number of loops surrounding a sequential kernel. 330 unsigned DeepestSequential = 0; 331 332 /// The maximal number of loops surrounding a parallel kernel. 333 unsigned DeepestParallel = 0; 334 335 /// Return the name to set for the ptx_kernel. 336 std::string getKernelFuncName(int Kernel_id); 337 338 private: 339 /// A vector of array base pointers for which a new ScopArrayInfo was created. 340 /// 341 /// This vector is used to delete the ScopArrayInfo when it is not needed any 342 /// more. 343 std::vector<Value *> LocalArrays; 344 345 /// A map from ScopArrays to their corresponding device allocations. 346 std::map<ScopArrayInfo *, Value *> DeviceAllocations; 347 348 /// The current GPU context. 349 Value *GPUContext; 350 351 /// The set of isl_ids allocated in the kernel 352 std::vector<isl_id *> KernelIds; 353 354 /// A module containing GPU code. 355 /// 356 /// This pointer is only set in case we are currently generating GPU code. 357 std::unique_ptr<Module> GPUModule; 358 359 /// The GPU program we generate code for. 360 gpu_prog *Prog; 361 362 /// The GPU Runtime implementation to use (OpenCL or CUDA). 363 GPURuntime Runtime; 364 365 /// The GPU Architecture to target. 366 GPUArch Arch; 367 368 /// Class to free isl_ids. 369 class IslIdDeleter { 370 public: 371 void operator()(__isl_take isl_id *Id) { isl_id_free(Id); }; 372 }; 373 374 /// A set containing all isl_ids allocated in a GPU kernel. 375 /// 376 /// By releasing this set all isl_ids will be freed. 377 std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs; 378 379 IslExprBuilder::IDToScopArrayInfoTy IDToSAI; 380 381 /// Create code for user-defined AST nodes. 382 /// 383 /// These AST nodes can be of type: 384 /// 385 /// - ScopStmt: A computational statement (TODO) 386 /// - Kernel: A GPU kernel call (TODO) 387 /// - Data-Transfer: A GPU <-> CPU data-transfer 388 /// - In-kernel synchronization 389 /// - In-kernel memory copy statement 390 /// 391 /// @param UserStmt The ast node to generate code for. 392 virtual void createUser(__isl_take isl_ast_node *UserStmt); 393 394 enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST }; 395 396 /// Create code for a data transfer statement 397 /// 398 /// @param TransferStmt The data transfer statement. 399 /// @param Direction The direction in which to transfer data. 400 void createDataTransfer(__isl_take isl_ast_node *TransferStmt, 401 enum DataDirection Direction); 402 403 /// Find llvm::Values referenced in GPU kernel. 404 /// 405 /// @param Kernel The kernel to scan for llvm::Values 406 /// 407 /// @returns A pair, whose first element contains the set of values 408 /// referenced by the kernel, and whose second element contains the 409 /// set of functions referenced by the kernel. All functions in the 410 /// second set satisfy isValidFunctionInKernel. 411 std::pair<SetVector<Value *>, SetVector<Function *>> 412 getReferencesInKernel(ppcg_kernel *Kernel); 413 414 /// Compute the sizes of the execution grid for a given kernel. 415 /// 416 /// @param Kernel The kernel to compute grid sizes for. 417 /// 418 /// @returns A tuple with grid sizes for X and Y dimension 419 std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel); 420 421 /// Creates a array that can be sent to the kernel on the device using a 422 /// host pointer. This is required for managed memory, when we directly send 423 /// host pointers to the device. 424 /// \note 425 /// This is to be used only with managed memory 426 Value *getOrCreateManagedDeviceArray(gpu_array_info *Array, 427 ScopArrayInfo *ArrayInfo); 428 429 /// Compute the sizes of the thread blocks for a given kernel. 430 /// 431 /// @param Kernel The kernel to compute thread block sizes for. 432 /// 433 /// @returns A tuple with thread block sizes for X, Y, and Z dimensions. 434 std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel); 435 436 /// Store a specific kernel launch parameter in the array of kernel launch 437 /// parameters. 438 /// 439 /// @param Parameters The list of parameters in which to store. 440 /// @param Param The kernel launch parameter to store. 441 /// @param Index The index in the parameter list, at which to store the 442 /// parameter. 443 void insertStoreParameter(Instruction *Parameters, Instruction *Param, 444 int Index); 445 446 /// Create kernel launch parameters. 447 /// 448 /// @param Kernel The kernel to create parameters for. 449 /// @param F The kernel function that has been created. 450 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 451 /// 452 /// @returns A stack allocated array with pointers to the parameter 453 /// values that are passed to the kernel. 454 Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F, 455 SetVector<Value *> SubtreeValues); 456 457 /// Create declarations for kernel variable. 458 /// 459 /// This includes shared memory declarations. 460 /// 461 /// @param Kernel The kernel definition to create variables for. 462 /// @param FN The function into which to generate the variables. 463 void createKernelVariables(ppcg_kernel *Kernel, Function *FN); 464 465 /// Add CUDA annotations to module. 466 /// 467 /// Add a set of CUDA annotations that declares the maximal block dimensions 468 /// that will be used to execute the CUDA kernel. This allows the NVIDIA 469 /// PTX compiler to bound the number of allocated registers to ensure the 470 /// resulting kernel is known to run with up to as many block dimensions 471 /// as specified here. 472 /// 473 /// @param M The module to add the annotations to. 474 /// @param BlockDimX The size of block dimension X. 475 /// @param BlockDimY The size of block dimension Y. 476 /// @param BlockDimZ The size of block dimension Z. 477 void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY, 478 Value *BlockDimZ); 479 480 /// Create GPU kernel. 481 /// 482 /// Code generate the kernel described by @p KernelStmt. 483 /// 484 /// @param KernelStmt The ast node to generate kernel code for. 485 void createKernel(__isl_take isl_ast_node *KernelStmt); 486 487 /// Generate code that computes the size of an array. 488 /// 489 /// @param Array The array for which to compute a size. 490 Value *getArraySize(gpu_array_info *Array); 491 492 /// Generate code to compute the minimal offset at which an array is accessed. 493 /// 494 /// The offset of an array is the minimal array location accessed in a scop. 495 /// 496 /// Example: 497 /// 498 /// for (long i = 0; i < 100; i++) 499 /// A[i + 42] += ... 500 /// 501 /// getArrayOffset(A) results in 42. 502 /// 503 /// @param Array The array for which to compute the offset. 504 /// @returns An llvm::Value that contains the offset of the array. 505 Value *getArrayOffset(gpu_array_info *Array); 506 507 /// Prepare the kernel arguments for kernel code generation 508 /// 509 /// @param Kernel The kernel to generate code for. 510 /// @param FN The function created for the kernel. 511 void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN); 512 513 /// Create kernel function. 514 /// 515 /// Create a kernel function located in a newly created module that can serve 516 /// as target for device code generation. Set the Builder to point to the 517 /// start block of this newly created function. 518 /// 519 /// @param Kernel The kernel to generate code for. 520 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 521 /// @param SubtreeFunctions The set of llvm::Functions referenced by this 522 /// kernel. 523 void createKernelFunction(ppcg_kernel *Kernel, 524 SetVector<Value *> &SubtreeValues, 525 SetVector<Function *> &SubtreeFunctions); 526 527 /// Create the declaration of a kernel function. 528 /// 529 /// The kernel function takes as arguments: 530 /// 531 /// - One i8 pointer for each external array reference used in the kernel. 532 /// - Host iterators 533 /// - Parameters 534 /// - Other LLVM Value references (TODO) 535 /// 536 /// @param Kernel The kernel to generate the function declaration for. 537 /// @param SubtreeValues The set of llvm::Values referenced by this kernel. 538 /// 539 /// @returns The newly declared function. 540 Function *createKernelFunctionDecl(ppcg_kernel *Kernel, 541 SetVector<Value *> &SubtreeValues); 542 543 /// Insert intrinsic functions to obtain thread and block ids. 544 /// 545 /// @param The kernel to generate the intrinsic functions for. 546 void insertKernelIntrinsics(ppcg_kernel *Kernel); 547 548 /// Setup the creation of functions referenced by the GPU kernel. 549 /// 550 /// 1. Create new function declarations in GPUModule which are the same as 551 /// SubtreeFunctions. 552 /// 553 /// 2. Populate IslNodeBuilder::ValueMap with mappings from 554 /// old functions (that come from the original module) to new functions 555 /// (that are created within GPUModule). That way, we generate references 556 /// to the correct function (in GPUModule) in BlockGenerator. 557 /// 558 /// @see IslNodeBuilder::ValueMap 559 /// @see BlockGenerator::GlobalMap 560 /// @see BlockGenerator::getNewValue 561 /// @see GPUNodeBuilder::getReferencesInKernel. 562 /// 563 /// @param SubtreeFunctions The set of llvm::Functions referenced by 564 /// this kernel. 565 void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions); 566 567 /// Create a global-to-shared or shared-to-global copy statement. 568 /// 569 /// @param CopyStmt The copy statement to generate code for 570 void createKernelCopy(ppcg_kernel_stmt *CopyStmt); 571 572 /// Create code for a ScopStmt called in @p Expr. 573 /// 574 /// @param Expr The expression containing the call. 575 /// @param KernelStmt The kernel statement referenced in the call. 576 void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt); 577 578 /// Create an in-kernel synchronization call. 579 void createKernelSync(); 580 581 /// Create a PTX assembly string for the current GPU kernel. 582 /// 583 /// @returns A string containing the corresponding PTX assembly code. 584 std::string createKernelASM(); 585 586 /// Remove references from the dominator tree to the kernel function @p F. 587 /// 588 /// @param F The function to remove references to. 589 void clearDominators(Function *F); 590 591 /// Remove references from scalar evolution to the kernel function @p F. 592 /// 593 /// @param F The function to remove references to. 594 void clearScalarEvolution(Function *F); 595 596 /// Remove references from loop info to the kernel function @p F. 597 /// 598 /// @param F The function to remove references to. 599 void clearLoops(Function *F); 600 601 /// Finalize the generation of the kernel function. 602 /// 603 /// Free the LLVM-IR module corresponding to the kernel and -- if requested -- 604 /// dump its IR to stderr. 605 /// 606 /// @returns The Assembly string of the kernel. 607 std::string finalizeKernelFunction(); 608 609 /// Finalize the generation of the kernel arguments. 610 /// 611 /// This function ensures that not-read-only scalars used in a kernel are 612 /// stored back to the global memory location they are backed with before 613 /// the kernel terminates. 614 /// 615 /// @params Kernel The kernel to finalize kernel arguments for. 616 void finalizeKernelArguments(ppcg_kernel *Kernel); 617 618 /// Create code that allocates memory to store arrays on device. 619 void allocateDeviceArrays(); 620 621 /// Free all allocated device arrays. 622 void freeDeviceArrays(); 623 624 /// Create a call to initialize the GPU context. 625 /// 626 /// @returns A pointer to the newly initialized context. 627 Value *createCallInitContext(); 628 629 /// Create a call to get the device pointer for a kernel allocation. 630 /// 631 /// @param Allocation The Polly GPU allocation 632 /// 633 /// @returns The device parameter corresponding to this allocation. 634 Value *createCallGetDevicePtr(Value *Allocation); 635 636 /// Create a call to free the GPU context. 637 /// 638 /// @param Context A pointer to an initialized GPU context. 639 void createCallFreeContext(Value *Context); 640 641 /// Create a call to allocate memory on the device. 642 /// 643 /// @param Size The size of memory to allocate 644 /// 645 /// @returns A pointer that identifies this allocation. 646 Value *createCallAllocateMemoryForDevice(Value *Size); 647 648 /// Create a call to free a device array. 649 /// 650 /// @param Array The device array to free. 651 void createCallFreeDeviceMemory(Value *Array); 652 653 /// Create a call to copy data from host to device. 654 /// 655 /// @param HostPtr A pointer to the host data that should be copied. 656 /// @param DevicePtr A device pointer specifying the location to copy to. 657 void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr, 658 Value *Size); 659 660 /// Create a call to copy data from device to host. 661 /// 662 /// @param DevicePtr A pointer to the device data that should be copied. 663 /// @param HostPtr A host pointer specifying the location to copy to. 664 void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr, 665 Value *Size); 666 667 /// Create a call to synchronize Host & Device. 668 /// \note 669 /// This is to be used only with managed memory. 670 void createCallSynchronizeDevice(); 671 672 /// Create a call to get a kernel from an assembly string. 673 /// 674 /// @param Buffer The string describing the kernel. 675 /// @param Entry The name of the kernel function to call. 676 /// 677 /// @returns A pointer to a kernel object 678 Value *createCallGetKernel(Value *Buffer, Value *Entry); 679 680 /// Create a call to free a GPU kernel. 681 /// 682 /// @param GPUKernel THe kernel to free. 683 void createCallFreeKernel(Value *GPUKernel); 684 685 /// Create a call to launch a GPU kernel. 686 /// 687 /// @param GPUKernel The kernel to launch. 688 /// @param GridDimX The size of the first grid dimension. 689 /// @param GridDimY The size of the second grid dimension. 690 /// @param GridBlockX The size of the first block dimension. 691 /// @param GridBlockY The size of the second block dimension. 692 /// @param GridBlockZ The size of the third block dimension. 693 /// @param Parameters A pointer to an array that contains itself pointers to 694 /// the parameter values passed for each kernel argument. 695 void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 696 Value *GridDimY, Value *BlockDimX, 697 Value *BlockDimY, Value *BlockDimZ, 698 Value *Parameters); 699 }; 700 701 std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) { 702 return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" + 703 std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id); 704 } 705 706 void GPUNodeBuilder::initializeAfterRTH() { 707 BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(), 708 &*Builder.GetInsertPoint(), &DT, &LI); 709 NewBB->setName("polly.acc.initialize"); 710 Builder.SetInsertPoint(&NewBB->front()); 711 712 GPUContext = createCallInitContext(); 713 714 if (!ManagedMemory) 715 allocateDeviceArrays(); 716 } 717 718 void GPUNodeBuilder::finalize() { 719 if (!ManagedMemory) 720 freeDeviceArrays(); 721 722 createCallFreeContext(GPUContext); 723 IslNodeBuilder::finalize(); 724 } 725 726 void GPUNodeBuilder::allocateDeviceArrays() { 727 assert(!ManagedMemory && "Managed memory will directly send host pointers " 728 "to the kernel. There is no need for device arrays"); 729 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 730 731 for (int i = 0; i < Prog->n_array; ++i) { 732 gpu_array_info *Array = &Prog->array[i]; 733 auto *ScopArray = (ScopArrayInfo *)Array->user; 734 std::string DevArrayName("p_dev_array_"); 735 DevArrayName.append(Array->name); 736 737 Value *ArraySize = getArraySize(Array); 738 Value *Offset = getArrayOffset(Array); 739 if (Offset) 740 ArraySize = Builder.CreateSub( 741 ArraySize, 742 Builder.CreateMul(Offset, 743 Builder.getInt64(ScopArray->getElemSizeInBytes()))); 744 Value *DevArray = createCallAllocateMemoryForDevice(ArraySize); 745 DevArray->setName(DevArrayName); 746 DeviceAllocations[ScopArray] = DevArray; 747 } 748 749 isl_ast_build_free(Build); 750 } 751 752 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX, 753 Value *BlockDimY, Value *BlockDimZ) { 754 auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations"); 755 756 for (auto &F : *M) { 757 if (F.getCallingConv() != CallingConv::PTX_Kernel) 758 continue; 759 760 Value *V[] = {BlockDimX, BlockDimY, BlockDimZ}; 761 762 Metadata *Elements[] = { 763 ValueAsMetadata::get(&F), MDString::get(M->getContext(), "maxntidx"), 764 ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"), 765 ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"), 766 ValueAsMetadata::get(V[2]), 767 }; 768 MDNode *Node = MDNode::get(M->getContext(), Elements); 769 AnnotationNode->addOperand(Node); 770 } 771 } 772 773 void GPUNodeBuilder::freeDeviceArrays() { 774 assert(!ManagedMemory && "Managed memory does not use device arrays"); 775 for (auto &Array : DeviceAllocations) 776 createCallFreeDeviceMemory(Array.second); 777 } 778 779 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) { 780 const char *Name = "polly_getKernel"; 781 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 782 Function *F = M->getFunction(Name); 783 784 // If F is not available, declare it. 785 if (!F) { 786 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 787 std::vector<Type *> Args; 788 Args.push_back(Builder.getInt8PtrTy()); 789 Args.push_back(Builder.getInt8PtrTy()); 790 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 791 F = Function::Create(Ty, Linkage, Name, M); 792 } 793 794 return Builder.CreateCall(F, {Buffer, Entry}); 795 } 796 797 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) { 798 const char *Name = "polly_getDevicePtr"; 799 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 800 Function *F = M->getFunction(Name); 801 802 // If F is not available, declare it. 803 if (!F) { 804 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 805 std::vector<Type *> Args; 806 Args.push_back(Builder.getInt8PtrTy()); 807 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 808 F = Function::Create(Ty, Linkage, Name, M); 809 } 810 811 return Builder.CreateCall(F, {Allocation}); 812 } 813 814 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX, 815 Value *GridDimY, Value *BlockDimX, 816 Value *BlockDimY, Value *BlockDimZ, 817 Value *Parameters) { 818 const char *Name = "polly_launchKernel"; 819 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 820 Function *F = M->getFunction(Name); 821 822 // If F is not available, declare it. 823 if (!F) { 824 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 825 std::vector<Type *> Args; 826 Args.push_back(Builder.getInt8PtrTy()); 827 Args.push_back(Builder.getInt32Ty()); 828 Args.push_back(Builder.getInt32Ty()); 829 Args.push_back(Builder.getInt32Ty()); 830 Args.push_back(Builder.getInt32Ty()); 831 Args.push_back(Builder.getInt32Ty()); 832 Args.push_back(Builder.getInt8PtrTy()); 833 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 834 F = Function::Create(Ty, Linkage, Name, M); 835 } 836 837 Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 838 BlockDimZ, Parameters}); 839 } 840 841 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) { 842 const char *Name = "polly_freeKernel"; 843 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 844 Function *F = M->getFunction(Name); 845 846 // If F is not available, declare it. 847 if (!F) { 848 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 849 std::vector<Type *> Args; 850 Args.push_back(Builder.getInt8PtrTy()); 851 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 852 F = Function::Create(Ty, Linkage, Name, M); 853 } 854 855 Builder.CreateCall(F, {GPUKernel}); 856 } 857 858 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) { 859 assert(!ManagedMemory && "Managed memory does not allocate or free memory " 860 "for device"); 861 const char *Name = "polly_freeDeviceMemory"; 862 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 863 Function *F = M->getFunction(Name); 864 865 // If F is not available, declare it. 866 if (!F) { 867 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 868 std::vector<Type *> Args; 869 Args.push_back(Builder.getInt8PtrTy()); 870 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 871 F = Function::Create(Ty, Linkage, Name, M); 872 } 873 874 Builder.CreateCall(F, {Array}); 875 } 876 877 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) { 878 assert(!ManagedMemory && "Managed memory does not allocate or free memory " 879 "for device"); 880 const char *Name = "polly_allocateMemoryForDevice"; 881 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 882 Function *F = M->getFunction(Name); 883 884 // If F is not available, declare it. 885 if (!F) { 886 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 887 std::vector<Type *> Args; 888 Args.push_back(Builder.getInt64Ty()); 889 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 890 F = Function::Create(Ty, Linkage, Name, M); 891 } 892 893 return Builder.CreateCall(F, {Size}); 894 } 895 896 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData, 897 Value *DeviceData, 898 Value *Size) { 899 assert(!ManagedMemory && "Managed memory does not transfer memory between " 900 "device and host"); 901 const char *Name = "polly_copyFromHostToDevice"; 902 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 903 Function *F = M->getFunction(Name); 904 905 // If F is not available, declare it. 906 if (!F) { 907 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 908 std::vector<Type *> Args; 909 Args.push_back(Builder.getInt8PtrTy()); 910 Args.push_back(Builder.getInt8PtrTy()); 911 Args.push_back(Builder.getInt64Ty()); 912 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 913 F = Function::Create(Ty, Linkage, Name, M); 914 } 915 916 Builder.CreateCall(F, {HostData, DeviceData, Size}); 917 } 918 919 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData, 920 Value *HostData, 921 Value *Size) { 922 assert(!ManagedMemory && "Managed memory does not transfer memory between " 923 "device and host"); 924 const char *Name = "polly_copyFromDeviceToHost"; 925 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 926 Function *F = M->getFunction(Name); 927 928 // If F is not available, declare it. 929 if (!F) { 930 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 931 std::vector<Type *> Args; 932 Args.push_back(Builder.getInt8PtrTy()); 933 Args.push_back(Builder.getInt8PtrTy()); 934 Args.push_back(Builder.getInt64Ty()); 935 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 936 F = Function::Create(Ty, Linkage, Name, M); 937 } 938 939 Builder.CreateCall(F, {DeviceData, HostData, Size}); 940 } 941 942 void GPUNodeBuilder::createCallSynchronizeDevice() { 943 assert(ManagedMemory && "explicit synchronization is only necessary for " 944 "managed memory"); 945 const char *Name = "polly_synchronizeDevice"; 946 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 947 Function *F = M->getFunction(Name); 948 949 // If F is not available, declare it. 950 if (!F) { 951 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 952 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false); 953 F = Function::Create(Ty, Linkage, Name, M); 954 } 955 956 Builder.CreateCall(F); 957 } 958 959 Value *GPUNodeBuilder::createCallInitContext() { 960 const char *Name; 961 962 switch (Runtime) { 963 case GPURuntime::CUDA: 964 Name = "polly_initContextCUDA"; 965 break; 966 case GPURuntime::OpenCL: 967 Name = "polly_initContextCL"; 968 break; 969 } 970 971 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 972 Function *F = M->getFunction(Name); 973 974 // If F is not available, declare it. 975 if (!F) { 976 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 977 std::vector<Type *> Args; 978 FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false); 979 F = Function::Create(Ty, Linkage, Name, M); 980 } 981 982 return Builder.CreateCall(F, {}); 983 } 984 985 void GPUNodeBuilder::createCallFreeContext(Value *Context) { 986 const char *Name = "polly_freeContext"; 987 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 988 Function *F = M->getFunction(Name); 989 990 // If F is not available, declare it. 991 if (!F) { 992 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage; 993 std::vector<Type *> Args; 994 Args.push_back(Builder.getInt8PtrTy()); 995 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false); 996 F = Function::Create(Ty, Linkage, Name, M); 997 } 998 999 Builder.CreateCall(F, {Context}); 1000 } 1001 1002 /// Check if one string is a prefix of another. 1003 /// 1004 /// @param String The string in which to look for the prefix. 1005 /// @param Prefix The prefix to look for. 1006 static bool isPrefix(std::string String, std::string Prefix) { 1007 return String.find(Prefix) == 0; 1008 } 1009 1010 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) { 1011 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1012 Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size); 1013 1014 if (!gpu_array_is_scalar(Array)) { 1015 auto OffsetDimZero = isl_multi_pw_aff_get_pw_aff(Array->bound, 0); 1016 isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero); 1017 1018 for (unsigned int i = 1; i < Array->n_index; i++) { 1019 isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i); 1020 isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1021 Res = isl_ast_expr_mul(Res, Expr); 1022 } 1023 1024 Value *NumElements = ExprBuilder.create(Res); 1025 if (NumElements->getType() != ArraySize->getType()) 1026 NumElements = Builder.CreateSExt(NumElements, ArraySize->getType()); 1027 ArraySize = Builder.CreateMul(ArraySize, NumElements); 1028 } 1029 isl_ast_build_free(Build); 1030 return ArraySize; 1031 } 1032 1033 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) { 1034 if (gpu_array_is_scalar(Array)) 1035 return nullptr; 1036 1037 isl_ast_build *Build = isl_ast_build_from_context(S.getContext()); 1038 1039 isl_set *Min = isl_set_lexmin(isl_set_copy(Array->extent)); 1040 1041 isl_set *ZeroSet = isl_set_universe(isl_set_get_space(Min)); 1042 1043 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) 1044 ZeroSet = isl_set_fix_si(ZeroSet, isl_dim_set, i, 0); 1045 1046 if (isl_set_is_subset(Min, ZeroSet)) { 1047 isl_set_free(Min); 1048 isl_set_free(ZeroSet); 1049 isl_ast_build_free(Build); 1050 return nullptr; 1051 } 1052 isl_set_free(ZeroSet); 1053 1054 isl_ast_expr *Result = 1055 isl_ast_expr_from_val(isl_val_int_from_si(isl_set_get_ctx(Min), 0)); 1056 1057 for (long i = 0; i < isl_set_dim(Min, isl_dim_set); i++) { 1058 if (i > 0) { 1059 isl_pw_aff *Bound_I = isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1); 1060 isl_ast_expr *BExpr = isl_ast_build_expr_from_pw_aff(Build, Bound_I); 1061 Result = isl_ast_expr_mul(Result, BExpr); 1062 } 1063 isl_pw_aff *DimMin = isl_set_dim_min(isl_set_copy(Min), i); 1064 isl_ast_expr *MExpr = isl_ast_build_expr_from_pw_aff(Build, DimMin); 1065 Result = isl_ast_expr_add(Result, MExpr); 1066 } 1067 1068 Value *ResultValue = ExprBuilder.create(Result); 1069 isl_set_free(Min); 1070 isl_ast_build_free(Build); 1071 1072 return ResultValue; 1073 } 1074 1075 Value *GPUNodeBuilder::getOrCreateManagedDeviceArray(gpu_array_info *Array, 1076 ScopArrayInfo *ArrayInfo) { 1077 1078 assert(ManagedMemory && "Only used when you wish to get a host " 1079 "pointer for sending data to the kernel, " 1080 "with managed memory"); 1081 std::map<ScopArrayInfo *, Value *>::iterator it; 1082 if ((it = DeviceAllocations.find(ArrayInfo)) != DeviceAllocations.end()) { 1083 return it->second; 1084 } else { 1085 Value *HostPtr; 1086 1087 if (gpu_array_is_scalar(Array)) 1088 HostPtr = BlockGen.getOrCreateAlloca(ArrayInfo); 1089 else 1090 HostPtr = ArrayInfo->getBasePtr(); 1091 1092 Value *Offset = getArrayOffset(Array); 1093 if (Offset) { 1094 HostPtr = Builder.CreatePointerCast( 1095 HostPtr, ArrayInfo->getElementType()->getPointerTo()); 1096 HostPtr = Builder.CreateGEP(HostPtr, Offset); 1097 } 1098 1099 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1100 DeviceAllocations[ArrayInfo] = HostPtr; 1101 return HostPtr; 1102 } 1103 } 1104 1105 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt, 1106 enum DataDirection Direction) { 1107 assert(!ManagedMemory && "Managed memory needs no data transfers"); 1108 isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt); 1109 isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0); 1110 isl_id *Id = isl_ast_expr_get_id(Arg); 1111 auto Array = (gpu_array_info *)isl_id_get_user(Id); 1112 auto ScopArray = (ScopArrayInfo *)(Array->user); 1113 1114 Value *Size = getArraySize(Array); 1115 Value *Offset = getArrayOffset(Array); 1116 Value *DevPtr = DeviceAllocations[ScopArray]; 1117 1118 Value *HostPtr; 1119 1120 if (gpu_array_is_scalar(Array)) 1121 HostPtr = BlockGen.getOrCreateAlloca(ScopArray); 1122 else 1123 HostPtr = ScopArray->getBasePtr(); 1124 1125 if (Offset) { 1126 HostPtr = Builder.CreatePointerCast( 1127 HostPtr, ScopArray->getElementType()->getPointerTo()); 1128 HostPtr = Builder.CreateGEP(HostPtr, Offset); 1129 } 1130 1131 HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy()); 1132 1133 if (Offset) { 1134 Size = Builder.CreateSub( 1135 Size, Builder.CreateMul( 1136 Offset, Builder.getInt64(ScopArray->getElemSizeInBytes()))); 1137 } 1138 1139 if (Direction == HOST_TO_DEVICE) 1140 createCallCopyFromHostToDevice(HostPtr, DevPtr, Size); 1141 else 1142 createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size); 1143 1144 isl_id_free(Id); 1145 isl_ast_expr_free(Arg); 1146 isl_ast_expr_free(Expr); 1147 isl_ast_node_free(TransferStmt); 1148 } 1149 1150 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) { 1151 isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt); 1152 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1153 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1154 isl_id_free(Id); 1155 isl_ast_expr_free(StmtExpr); 1156 1157 const char *Str = isl_id_get_name(Id); 1158 if (!strcmp(Str, "kernel")) { 1159 createKernel(UserStmt); 1160 isl_ast_expr_free(Expr); 1161 return; 1162 } 1163 if (!strcmp(Str, "init_device")) { 1164 initializeAfterRTH(); 1165 isl_ast_node_free(UserStmt); 1166 isl_ast_expr_free(Expr); 1167 return; 1168 } 1169 if (!strcmp(Str, "clear_device")) { 1170 finalize(); 1171 isl_ast_node_free(UserStmt); 1172 isl_ast_expr_free(Expr); 1173 return; 1174 } 1175 if (isPrefix(Str, "to_device")) { 1176 if (!ManagedMemory) 1177 createDataTransfer(UserStmt, HOST_TO_DEVICE); 1178 else 1179 isl_ast_node_free(UserStmt); 1180 1181 isl_ast_expr_free(Expr); 1182 return; 1183 } 1184 1185 if (isPrefix(Str, "from_device")) { 1186 if (!ManagedMemory) { 1187 createDataTransfer(UserStmt, DEVICE_TO_HOST); 1188 } else { 1189 createCallSynchronizeDevice(); 1190 isl_ast_node_free(UserStmt); 1191 } 1192 isl_ast_expr_free(Expr); 1193 return; 1194 } 1195 1196 isl_id *Anno = isl_ast_node_get_annotation(UserStmt); 1197 struct ppcg_kernel_stmt *KernelStmt = 1198 (struct ppcg_kernel_stmt *)isl_id_get_user(Anno); 1199 isl_id_free(Anno); 1200 1201 switch (KernelStmt->type) { 1202 case ppcg_kernel_domain: 1203 createScopStmt(Expr, KernelStmt); 1204 isl_ast_node_free(UserStmt); 1205 return; 1206 case ppcg_kernel_copy: 1207 createKernelCopy(KernelStmt); 1208 isl_ast_expr_free(Expr); 1209 isl_ast_node_free(UserStmt); 1210 return; 1211 case ppcg_kernel_sync: 1212 createKernelSync(); 1213 isl_ast_expr_free(Expr); 1214 isl_ast_node_free(UserStmt); 1215 return; 1216 } 1217 1218 isl_ast_expr_free(Expr); 1219 isl_ast_node_free(UserStmt); 1220 return; 1221 } 1222 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) { 1223 isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index); 1224 LocalIndex = isl_ast_expr_address_of(LocalIndex); 1225 Value *LocalAddr = ExprBuilder.create(LocalIndex); 1226 isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index); 1227 Index = isl_ast_expr_address_of(Index); 1228 Value *GlobalAddr = ExprBuilder.create(Index); 1229 1230 if (KernelStmt->u.c.read) { 1231 LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read"); 1232 Builder.CreateStore(Load, LocalAddr); 1233 } else { 1234 LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write"); 1235 Builder.CreateStore(Load, GlobalAddr); 1236 } 1237 } 1238 1239 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr, 1240 ppcg_kernel_stmt *KernelStmt) { 1241 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1242 isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr; 1243 1244 LoopToScevMapT LTS; 1245 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 1246 1247 createSubstitutions(Expr, Stmt, LTS); 1248 1249 if (Stmt->isBlockStmt()) 1250 BlockGen.copyStmt(*Stmt, LTS, Indexes); 1251 else 1252 RegionGen.copyStmt(*Stmt, LTS, Indexes); 1253 } 1254 1255 void GPUNodeBuilder::createKernelSync() { 1256 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1257 1258 Function *Sync; 1259 1260 switch (Arch) { 1261 case GPUArch::NVPTX64: 1262 Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0); 1263 break; 1264 } 1265 1266 Builder.CreateCall(Sync, {}); 1267 } 1268 1269 /// Collect llvm::Values referenced from @p Node 1270 /// 1271 /// This function only applies to isl_ast_nodes that are user_nodes referring 1272 /// to a ScopStmt. All other node types are ignore. 1273 /// 1274 /// @param Node The node to collect references for. 1275 /// @param User A user pointer used as storage for the data that is collected. 1276 /// 1277 /// @returns isl_bool_true if data could be collected successfully. 1278 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) { 1279 if (isl_ast_node_get_type(Node) != isl_ast_node_user) 1280 return isl_bool_true; 1281 1282 isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node); 1283 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 1284 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 1285 const char *Str = isl_id_get_name(Id); 1286 isl_id_free(Id); 1287 isl_ast_expr_free(StmtExpr); 1288 isl_ast_expr_free(Expr); 1289 1290 if (!isPrefix(Str, "Stmt")) 1291 return isl_bool_true; 1292 1293 Id = isl_ast_node_get_annotation(Node); 1294 auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id); 1295 auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt; 1296 isl_id_free(Id); 1297 1298 addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */); 1299 1300 return isl_bool_true; 1301 } 1302 1303 /// Check if F is a function that we can code-generate in a GPU kernel. 1304 static bool isValidFunctionInKernel(llvm::Function *F) { 1305 assert(F && "F is an invalid pointer"); 1306 // We string compare against the name of the function to allow 1307 // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and 1308 // "llvm.copysign". 1309 const StringRef Name = F->getName(); 1310 return F->isIntrinsic() && 1311 (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") || 1312 Name.startswith("llvm.copysign")); 1313 } 1314 1315 /// Do not take `Function` as a subtree value. 1316 /// 1317 /// We try to take the reference of all subtree values and pass them along 1318 /// to the kernel from the host. Taking an address of any function and 1319 /// trying to pass along is nonsensical. Only allow `Value`s that are not 1320 /// `Function`s. 1321 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); } 1322 1323 /// Return `Function`s from `RawSubtreeValues`. 1324 static SetVector<Function *> 1325 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) { 1326 SetVector<Function *> SubtreeFunctions; 1327 for (Value *It : RawSubtreeValues) { 1328 Function *F = dyn_cast<Function>(It); 1329 if (F) { 1330 assert(isValidFunctionInKernel(F) && "Code should have bailed out by " 1331 "this point if an invalid function " 1332 "were present in a kernel."); 1333 SubtreeFunctions.insert(F); 1334 } 1335 } 1336 return SubtreeFunctions; 1337 } 1338 1339 std::pair<SetVector<Value *>, SetVector<Function *>> 1340 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) { 1341 SetVector<Value *> SubtreeValues; 1342 SetVector<const SCEV *> SCEVs; 1343 SetVector<const Loop *> Loops; 1344 SubtreeReferences References = { 1345 LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()}; 1346 1347 for (const auto &I : IDToValue) 1348 SubtreeValues.insert(I.second); 1349 1350 isl_ast_node_foreach_descendant_top_down( 1351 Kernel->tree, collectReferencesInGPUStmt, &References); 1352 1353 for (const SCEV *Expr : SCEVs) 1354 findValues(Expr, SE, SubtreeValues); 1355 1356 for (auto &SAI : S.arrays()) 1357 SubtreeValues.remove(SAI->getBasePtr()); 1358 1359 isl_space *Space = S.getParamSpace(); 1360 for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1361 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i); 1362 assert(IDToValue.count(Id)); 1363 Value *Val = IDToValue[Id]; 1364 SubtreeValues.remove(Val); 1365 isl_id_free(Id); 1366 } 1367 isl_space_free(Space); 1368 1369 for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) { 1370 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1371 assert(IDToValue.count(Id)); 1372 Value *Val = IDToValue[Id]; 1373 SubtreeValues.remove(Val); 1374 isl_id_free(Id); 1375 } 1376 1377 // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions 1378 // SubtreeValues. This is important, because we should not lose any 1379 // SubtreeValues in the process of constructing the 1380 // "ValidSubtree{Values, Functions} sets. Nor should the set 1381 // ValidSubtree{Values, Functions} have any common element. 1382 auto ValidSubtreeValuesIt = 1383 make_filter_range(SubtreeValues, isValidSubtreeValue); 1384 SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(), 1385 ValidSubtreeValuesIt.end()); 1386 SetVector<Function *> ValidSubtreeFunctions( 1387 getFunctionsFromRawSubtreeValues(SubtreeValues)); 1388 1389 // @see IslNodeBuilder::getReferencesInSubtree 1390 SetVector<Value *> ReplacedValues; 1391 for (Value *V : ValidSubtreeValues) { 1392 auto It = ValueMap.find(V); 1393 if (It == ValueMap.end()) 1394 ReplacedValues.insert(V); 1395 else 1396 ReplacedValues.insert(It->second); 1397 } 1398 return std::make_pair(ReplacedValues, ValidSubtreeFunctions); 1399 } 1400 1401 void GPUNodeBuilder::clearDominators(Function *F) { 1402 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 1403 std::vector<BasicBlock *> Nodes; 1404 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 1405 Nodes.push_back(I->getBlock()); 1406 1407 for (BasicBlock *BB : Nodes) 1408 DT.eraseNode(BB); 1409 } 1410 1411 void GPUNodeBuilder::clearScalarEvolution(Function *F) { 1412 for (BasicBlock &BB : *F) { 1413 Loop *L = LI.getLoopFor(&BB); 1414 if (L) 1415 SE.forgetLoop(L); 1416 } 1417 } 1418 1419 void GPUNodeBuilder::clearLoops(Function *F) { 1420 for (BasicBlock &BB : *F) { 1421 Loop *L = LI.getLoopFor(&BB); 1422 if (L) 1423 SE.forgetLoop(L); 1424 LI.removeBlock(&BB); 1425 } 1426 } 1427 1428 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) { 1429 std::vector<Value *> Sizes; 1430 isl_ast_build *Context = isl_ast_build_from_context(S.getContext()); 1431 1432 for (long i = 0; i < Kernel->n_grid; i++) { 1433 isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i); 1434 isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size); 1435 Value *Res = ExprBuilder.create(GridSize); 1436 Res = Builder.CreateTrunc(Res, Builder.getInt32Ty()); 1437 Sizes.push_back(Res); 1438 } 1439 isl_ast_build_free(Context); 1440 1441 for (long i = Kernel->n_grid; i < 3; i++) 1442 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1443 1444 return std::make_tuple(Sizes[0], Sizes[1]); 1445 } 1446 1447 std::tuple<Value *, Value *, Value *> 1448 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) { 1449 std::vector<Value *> Sizes; 1450 1451 for (long i = 0; i < Kernel->n_block; i++) { 1452 Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]); 1453 Sizes.push_back(Res); 1454 } 1455 1456 for (long i = Kernel->n_block; i < 3; i++) 1457 Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1)); 1458 1459 return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]); 1460 } 1461 1462 void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters, 1463 Instruction *Param, int Index) { 1464 Value *Slot = Builder.CreateGEP( 1465 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1466 Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1467 Builder.CreateStore(ParamTyped, Slot); 1468 } 1469 1470 Value * 1471 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F, 1472 SetVector<Value *> SubtreeValues) { 1473 const int NumArgs = F->arg_size(); 1474 std::vector<int> ArgSizes(NumArgs); 1475 1476 Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs); 1477 1478 BasicBlock *EntryBlock = 1479 &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1480 auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace(); 1481 std::string Launch = "polly_launch_" + std::to_string(Kernel->id); 1482 Instruction *Parameters = new AllocaInst( 1483 ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator()); 1484 1485 int Index = 0; 1486 for (long i = 0; i < Prog->n_array; i++) { 1487 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1488 continue; 1489 1490 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1491 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1492 1493 ArgSizes[Index] = SAI->getElemSizeInBytes(); 1494 1495 Value *DevArray = nullptr; 1496 if (ManagedMemory) { 1497 DevArray = getOrCreateManagedDeviceArray( 1498 &Prog->array[i], const_cast<ScopArrayInfo *>(SAI)); 1499 } else { 1500 DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)]; 1501 DevArray = createCallGetDevicePtr(DevArray); 1502 } 1503 assert(DevArray != nullptr && "Array to be offloaded to device not " 1504 "initialized"); 1505 Value *Offset = getArrayOffset(&Prog->array[i]); 1506 1507 if (Offset) { 1508 DevArray = Builder.CreatePointerCast( 1509 DevArray, SAI->getElementType()->getPointerTo()); 1510 DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset)); 1511 DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy()); 1512 } 1513 Value *Slot = Builder.CreateGEP( 1514 Parameters, {Builder.getInt64(0), Builder.getInt64(Index)}); 1515 1516 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1517 Value *ValPtr = nullptr; 1518 if (ManagedMemory) 1519 ValPtr = DevArray; 1520 else 1521 ValPtr = BlockGen.getOrCreateAlloca(SAI); 1522 1523 assert(ValPtr != nullptr && "ValPtr that should point to a valid object" 1524 " to be stored into Parameters"); 1525 Value *ValPtrCast = 1526 Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy()); 1527 Builder.CreateStore(ValPtrCast, Slot); 1528 } else { 1529 Instruction *Param = 1530 new AllocaInst(Builder.getInt8PtrTy(), AddressSpace, 1531 Launch + "_param_" + std::to_string(Index), 1532 EntryBlock->getTerminator()); 1533 Builder.CreateStore(DevArray, Param); 1534 Value *ParamTyped = 1535 Builder.CreatePointerCast(Param, Builder.getInt8PtrTy()); 1536 Builder.CreateStore(ParamTyped, Slot); 1537 } 1538 Index++; 1539 } 1540 1541 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1542 1543 for (long i = 0; i < NumHostIters; i++) { 1544 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1545 Value *Val = IDToValue[Id]; 1546 isl_id_free(Id); 1547 1548 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1549 1550 Instruction *Param = 1551 new AllocaInst(Val->getType(), AddressSpace, 1552 Launch + "_param_" + std::to_string(Index), 1553 EntryBlock->getTerminator()); 1554 Builder.CreateStore(Val, Param); 1555 insertStoreParameter(Parameters, Param, Index); 1556 Index++; 1557 } 1558 1559 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1560 1561 for (long i = 0; i < NumVars; i++) { 1562 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1563 Value *Val = IDToValue[Id]; 1564 if (ValueMap.count(Val)) 1565 Val = ValueMap[Val]; 1566 isl_id_free(Id); 1567 1568 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1569 1570 Instruction *Param = 1571 new AllocaInst(Val->getType(), AddressSpace, 1572 Launch + "_param_" + std::to_string(Index), 1573 EntryBlock->getTerminator()); 1574 Builder.CreateStore(Val, Param); 1575 insertStoreParameter(Parameters, Param, Index); 1576 Index++; 1577 } 1578 1579 for (auto Val : SubtreeValues) { 1580 ArgSizes[Index] = computeSizeInBytes(Val->getType()); 1581 1582 Instruction *Param = 1583 new AllocaInst(Val->getType(), AddressSpace, 1584 Launch + "_param_" + std::to_string(Index), 1585 EntryBlock->getTerminator()); 1586 Builder.CreateStore(Val, Param); 1587 insertStoreParameter(Parameters, Param, Index); 1588 Index++; 1589 } 1590 1591 for (int i = 0; i < NumArgs; i++) { 1592 Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]); 1593 Instruction *Param = 1594 new AllocaInst(Builder.getInt32Ty(), AddressSpace, 1595 Launch + "_param_size_" + std::to_string(i), 1596 EntryBlock->getTerminator()); 1597 Builder.CreateStore(Val, Param); 1598 insertStoreParameter(Parameters, Param, Index); 1599 Index++; 1600 } 1601 1602 auto Location = EntryBlock->getTerminator(); 1603 return new BitCastInst(Parameters, Builder.getInt8PtrTy(), 1604 Launch + "_params_i8ptr", Location); 1605 } 1606 1607 void GPUNodeBuilder::setupKernelSubtreeFunctions( 1608 SetVector<Function *> SubtreeFunctions) { 1609 for (auto Fn : SubtreeFunctions) { 1610 const std::string ClonedFnName = Fn->getName(); 1611 Function *Clone = GPUModule->getFunction(ClonedFnName); 1612 if (!Clone) 1613 Clone = 1614 Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage, 1615 ClonedFnName, GPUModule.get()); 1616 assert(Clone && "Expected cloned function to be initialized."); 1617 assert(ValueMap.find(Fn) == ValueMap.end() && 1618 "Fn already present in ValueMap"); 1619 ValueMap[Fn] = Clone; 1620 } 1621 } 1622 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) { 1623 isl_id *Id = isl_ast_node_get_annotation(KernelStmt); 1624 ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id); 1625 isl_id_free(Id); 1626 isl_ast_node_free(KernelStmt); 1627 1628 if (Kernel->n_grid > 1) 1629 DeepestParallel = 1630 std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set)); 1631 else 1632 DeepestSequential = 1633 std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set)); 1634 1635 Value *BlockDimX, *BlockDimY, *BlockDimZ; 1636 std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel); 1637 1638 SetVector<Value *> SubtreeValues; 1639 SetVector<Function *> SubtreeFunctions; 1640 std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel); 1641 1642 assert(Kernel->tree && "Device AST of kernel node is empty"); 1643 1644 Instruction &HostInsertPoint = *Builder.GetInsertPoint(); 1645 IslExprBuilder::IDToValueTy HostIDs = IDToValue; 1646 ValueMapT HostValueMap = ValueMap; 1647 BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap; 1648 ScalarMap.clear(); 1649 1650 SetVector<const Loop *> Loops; 1651 1652 // Create for all loops we depend on values that contain the current loop 1653 // iteration. These values are necessary to generate code for SCEVs that 1654 // depend on such loops. As a result we need to pass them to the subfunction. 1655 for (const Loop *L : Loops) { 1656 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1657 SE.getUnknown(Builder.getInt64(1)), 1658 L, SCEV::FlagAnyWrap); 1659 Value *V = generateSCEV(OuterLIV); 1660 OutsideLoopIterations[L] = SE.getUnknown(V); 1661 SubtreeValues.insert(V); 1662 } 1663 1664 createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions); 1665 setupKernelSubtreeFunctions(SubtreeFunctions); 1666 1667 create(isl_ast_node_copy(Kernel->tree)); 1668 1669 finalizeKernelArguments(Kernel); 1670 Function *F = Builder.GetInsertBlock()->getParent(); 1671 addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ); 1672 clearDominators(F); 1673 clearScalarEvolution(F); 1674 clearLoops(F); 1675 1676 IDToValue = HostIDs; 1677 1678 ValueMap = std::move(HostValueMap); 1679 ScalarMap = std::move(HostScalarMap); 1680 EscapeMap.clear(); 1681 IDToSAI.clear(); 1682 Annotator.resetAlternativeAliasBases(); 1683 for (auto &BasePtr : LocalArrays) 1684 S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array); 1685 LocalArrays.clear(); 1686 1687 std::string ASMString = finalizeKernelFunction(); 1688 Builder.SetInsertPoint(&HostInsertPoint); 1689 Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues); 1690 1691 std::string Name = getKernelFuncName(Kernel->id); 1692 Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name); 1693 Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name"); 1694 Value *GPUKernel = createCallGetKernel(KernelString, NameString); 1695 1696 Value *GridDimX, *GridDimY; 1697 std::tie(GridDimX, GridDimY) = getGridSizes(Kernel); 1698 1699 createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY, 1700 BlockDimZ, Parameters); 1701 createCallFreeKernel(GPUKernel); 1702 1703 for (auto Id : KernelIds) 1704 isl_id_free(Id); 1705 1706 KernelIds.clear(); 1707 } 1708 1709 /// Compute the DataLayout string for the NVPTX backend. 1710 /// 1711 /// @param is64Bit Are we looking for a 64 bit architecture? 1712 static std::string computeNVPTXDataLayout(bool is64Bit) { 1713 std::string Ret = ""; 1714 1715 if (!is64Bit) { 1716 Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1717 "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1718 "64-v128:128:128-n16:32:64"; 1719 } else { 1720 Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:" 1721 "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:" 1722 "64-v128:128:128-n16:32:64"; 1723 } 1724 1725 return Ret; 1726 } 1727 1728 Function * 1729 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel, 1730 SetVector<Value *> &SubtreeValues) { 1731 std::vector<Type *> Args; 1732 std::string Identifier = getKernelFuncName(Kernel->id); 1733 1734 for (long i = 0; i < Prog->n_array; i++) { 1735 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1736 continue; 1737 1738 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1739 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1740 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id); 1741 Args.push_back(SAI->getElementType()); 1742 } else { 1743 static const int UseGlobalMemory = 1; 1744 Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory)); 1745 } 1746 } 1747 1748 int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set); 1749 1750 for (long i = 0; i < NumHostIters; i++) 1751 Args.push_back(Builder.getInt64Ty()); 1752 1753 int NumVars = isl_space_dim(Kernel->space, isl_dim_param); 1754 1755 for (long i = 0; i < NumVars; i++) { 1756 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1757 Value *Val = IDToValue[Id]; 1758 isl_id_free(Id); 1759 Args.push_back(Val->getType()); 1760 } 1761 1762 for (auto *V : SubtreeValues) 1763 Args.push_back(V->getType()); 1764 1765 auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false); 1766 auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier, 1767 GPUModule.get()); 1768 1769 switch (Arch) { 1770 case GPUArch::NVPTX64: 1771 FN->setCallingConv(CallingConv::PTX_Kernel); 1772 break; 1773 } 1774 1775 auto Arg = FN->arg_begin(); 1776 for (long i = 0; i < Kernel->n_array; i++) { 1777 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1778 continue; 1779 1780 Arg->setName(Kernel->array[i].array->name); 1781 1782 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1783 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1784 Type *EleTy = SAI->getElementType(); 1785 Value *Val = &*Arg; 1786 SmallVector<const SCEV *, 4> Sizes; 1787 isl_ast_build *Build = 1788 isl_ast_build_from_context(isl_set_copy(Prog->context)); 1789 Sizes.push_back(nullptr); 1790 for (long j = 1; j < Kernel->array[i].array->n_index; j++) { 1791 isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff( 1792 Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j)); 1793 auto V = ExprBuilder.create(DimSize); 1794 Sizes.push_back(SE.getSCEV(V)); 1795 } 1796 const ScopArrayInfo *SAIRep = 1797 S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array); 1798 LocalArrays.push_back(Val); 1799 1800 isl_ast_build_free(Build); 1801 KernelIds.push_back(Id); 1802 IDToSAI[Id] = SAIRep; 1803 Arg++; 1804 } 1805 1806 for (long i = 0; i < NumHostIters; i++) { 1807 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i); 1808 Arg->setName(isl_id_get_name(Id)); 1809 IDToValue[Id] = &*Arg; 1810 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1811 Arg++; 1812 } 1813 1814 for (long i = 0; i < NumVars; i++) { 1815 isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i); 1816 Arg->setName(isl_id_get_name(Id)); 1817 Value *Val = IDToValue[Id]; 1818 ValueMap[Val] = &*Arg; 1819 IDToValue[Id] = &*Arg; 1820 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1821 Arg++; 1822 } 1823 1824 for (auto *V : SubtreeValues) { 1825 Arg->setName(V->getName()); 1826 ValueMap[V] = &*Arg; 1827 Arg++; 1828 } 1829 1830 return FN; 1831 } 1832 1833 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) { 1834 Intrinsic::ID IntrinsicsBID[2]; 1835 Intrinsic::ID IntrinsicsTID[3]; 1836 1837 switch (Arch) { 1838 case GPUArch::NVPTX64: 1839 IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x; 1840 IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y; 1841 1842 IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x; 1843 IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y; 1844 IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z; 1845 break; 1846 } 1847 1848 auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable { 1849 std::string Name = isl_id_get_name(Id); 1850 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1851 Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr); 1852 Value *Val = Builder.CreateCall(IntrinsicFn, {}); 1853 Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name); 1854 IDToValue[Id] = Val; 1855 KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id)); 1856 }; 1857 1858 for (int i = 0; i < Kernel->n_grid; ++i) { 1859 isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i); 1860 addId(Id, IntrinsicsBID[i]); 1861 } 1862 1863 for (int i = 0; i < Kernel->n_block; ++i) { 1864 isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i); 1865 addId(Id, IntrinsicsTID[i]); 1866 } 1867 } 1868 1869 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) { 1870 auto Arg = FN->arg_begin(); 1871 for (long i = 0; i < Kernel->n_array; i++) { 1872 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1873 continue; 1874 1875 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1876 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1877 isl_id_free(Id); 1878 1879 if (SAI->getNumberOfDimensions() > 0) { 1880 Arg++; 1881 continue; 1882 } 1883 1884 Value *Val = &*Arg; 1885 1886 if (!gpu_array_is_read_only_scalar(&Prog->array[i])) { 1887 Type *TypePtr = SAI->getElementType()->getPointerTo(); 1888 Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr); 1889 Val = Builder.CreateLoad(TypedArgPtr); 1890 } 1891 1892 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 1893 Builder.CreateStore(Val, Alloca); 1894 1895 Arg++; 1896 } 1897 } 1898 1899 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) { 1900 auto *FN = Builder.GetInsertBlock()->getParent(); 1901 auto Arg = FN->arg_begin(); 1902 1903 bool StoredScalar = false; 1904 for (long i = 0; i < Kernel->n_array; i++) { 1905 if (!ppcg_kernel_requires_array_argument(Kernel, i)) 1906 continue; 1907 1908 isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set); 1909 const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id)); 1910 isl_id_free(Id); 1911 1912 if (SAI->getNumberOfDimensions() > 0) { 1913 Arg++; 1914 continue; 1915 } 1916 1917 if (gpu_array_is_read_only_scalar(&Prog->array[i])) { 1918 Arg++; 1919 continue; 1920 } 1921 1922 Value *Alloca = BlockGen.getOrCreateAlloca(SAI); 1923 Value *ArgPtr = &*Arg; 1924 Type *TypePtr = SAI->getElementType()->getPointerTo(); 1925 Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr); 1926 Value *Val = Builder.CreateLoad(Alloca); 1927 Builder.CreateStore(Val, TypedArgPtr); 1928 StoredScalar = true; 1929 1930 Arg++; 1931 } 1932 1933 if (StoredScalar) 1934 /// In case more than one thread contains scalar stores, the generated 1935 /// code might be incorrect, if we only store at the end of the kernel. 1936 /// To support this case we need to store these scalars back at each 1937 /// memory store or at least before each kernel barrier. 1938 if (Kernel->n_block != 0 || Kernel->n_grid != 0) 1939 BuildSuccessful = 0; 1940 } 1941 1942 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) { 1943 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 1944 1945 for (int i = 0; i < Kernel->n_var; ++i) { 1946 struct ppcg_kernel_var &Var = Kernel->var[i]; 1947 isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set); 1948 Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType(); 1949 1950 Type *ArrayTy = EleTy; 1951 SmallVector<const SCEV *, 4> Sizes; 1952 1953 Sizes.push_back(nullptr); 1954 for (unsigned int j = 1; j < Var.array->n_index; ++j) { 1955 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1956 long Bound = isl_val_get_num_si(Val); 1957 isl_val_free(Val); 1958 Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound)); 1959 } 1960 1961 for (int j = Var.array->n_index - 1; j >= 0; --j) { 1962 isl_val *Val = isl_vec_get_element_val(Var.size, j); 1963 long Bound = isl_val_get_num_si(Val); 1964 isl_val_free(Val); 1965 ArrayTy = ArrayType::get(ArrayTy, Bound); 1966 } 1967 1968 const ScopArrayInfo *SAI; 1969 Value *Allocation; 1970 if (Var.type == ppcg_access_shared) { 1971 auto GlobalVar = new GlobalVariable( 1972 *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, 1973 nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3); 1974 GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8); 1975 GlobalVar->setInitializer(Constant::getNullValue(ArrayTy)); 1976 1977 Allocation = GlobalVar; 1978 } else if (Var.type == ppcg_access_private) { 1979 Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array"); 1980 } else { 1981 llvm_unreachable("unknown variable type"); 1982 } 1983 SAI = 1984 S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array); 1985 Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr); 1986 IDToValue[Id] = Allocation; 1987 LocalArrays.push_back(Allocation); 1988 KernelIds.push_back(Id); 1989 IDToSAI[Id] = SAI; 1990 } 1991 } 1992 1993 void GPUNodeBuilder::createKernelFunction( 1994 ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues, 1995 SetVector<Function *> &SubtreeFunctions) { 1996 std::string Identifier = getKernelFuncName(Kernel->id); 1997 GPUModule.reset(new Module(Identifier, Builder.getContext())); 1998 1999 switch (Arch) { 2000 case GPUArch::NVPTX64: 2001 if (Runtime == GPURuntime::CUDA) 2002 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda")); 2003 else if (Runtime == GPURuntime::OpenCL) 2004 GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl")); 2005 GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */)); 2006 break; 2007 } 2008 2009 Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues); 2010 2011 BasicBlock *PrevBlock = Builder.GetInsertBlock(); 2012 auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN); 2013 2014 DT.addNewBlock(EntryBlock, PrevBlock); 2015 2016 Builder.SetInsertPoint(EntryBlock); 2017 Builder.CreateRetVoid(); 2018 Builder.SetInsertPoint(EntryBlock, EntryBlock->begin()); 2019 2020 ScopDetection::markFunctionAsInvalid(FN); 2021 2022 prepareKernelArguments(Kernel, FN); 2023 createKernelVariables(Kernel, FN); 2024 insertKernelIntrinsics(Kernel); 2025 } 2026 2027 std::string GPUNodeBuilder::createKernelASM() { 2028 llvm::Triple GPUTriple; 2029 2030 switch (Arch) { 2031 case GPUArch::NVPTX64: 2032 switch (Runtime) { 2033 case GPURuntime::CUDA: 2034 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda")); 2035 break; 2036 case GPURuntime::OpenCL: 2037 GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl")); 2038 break; 2039 } 2040 break; 2041 } 2042 2043 std::string ErrMsg; 2044 auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg); 2045 2046 if (!GPUTarget) { 2047 errs() << ErrMsg << "\n"; 2048 return ""; 2049 } 2050 2051 TargetOptions Options; 2052 Options.UnsafeFPMath = FastMath; 2053 2054 std::string subtarget; 2055 2056 switch (Arch) { 2057 case GPUArch::NVPTX64: 2058 subtarget = CudaVersion; 2059 break; 2060 } 2061 2062 std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine( 2063 GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>())); 2064 2065 SmallString<0> ASMString; 2066 raw_svector_ostream ASMStream(ASMString); 2067 llvm::legacy::PassManager PM; 2068 2069 PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis())); 2070 2071 if (TargetM->addPassesToEmitFile( 2072 PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) { 2073 errs() << "The target does not support generation of this file type!\n"; 2074 return ""; 2075 } 2076 2077 PM.run(*GPUModule); 2078 2079 return ASMStream.str(); 2080 } 2081 2082 std::string GPUNodeBuilder::finalizeKernelFunction() { 2083 2084 if (verifyModule(*GPUModule)) { 2085 DEBUG(dbgs() << "verifyModule failed on module:\n"; 2086 GPUModule->print(dbgs(), nullptr); dbgs() << "\n";); 2087 DEBUG(dbgs() << "verifyModule Error:\n"; 2088 verifyModule(*GPUModule, &dbgs());); 2089 2090 if (FailOnVerifyModuleFailure) 2091 llvm_unreachable("VerifyModule failed."); 2092 2093 BuildSuccessful = false; 2094 return ""; 2095 } 2096 2097 if (DumpKernelIR) 2098 outs() << *GPUModule << "\n"; 2099 2100 // Optimize module. 2101 llvm::legacy::PassManager OptPasses; 2102 PassManagerBuilder PassBuilder; 2103 PassBuilder.OptLevel = 3; 2104 PassBuilder.SizeLevel = 0; 2105 PassBuilder.populateModulePassManager(OptPasses); 2106 OptPasses.run(*GPUModule); 2107 2108 std::string Assembly = createKernelASM(); 2109 2110 if (DumpKernelASM) 2111 outs() << Assembly << "\n"; 2112 2113 GPUModule.release(); 2114 KernelIDs.clear(); 2115 2116 return Assembly; 2117 } 2118 2119 namespace { 2120 class PPCGCodeGeneration : public ScopPass { 2121 public: 2122 static char ID; 2123 2124 GPURuntime Runtime = GPURuntime::CUDA; 2125 2126 GPUArch Architecture = GPUArch::NVPTX64; 2127 2128 /// The scop that is currently processed. 2129 Scop *S; 2130 2131 LoopInfo *LI; 2132 DominatorTree *DT; 2133 ScalarEvolution *SE; 2134 const DataLayout *DL; 2135 RegionInfo *RI; 2136 2137 PPCGCodeGeneration() : ScopPass(ID) {} 2138 2139 /// Construct compilation options for PPCG. 2140 /// 2141 /// @returns The compilation options. 2142 ppcg_options *createPPCGOptions() { 2143 auto DebugOptions = 2144 (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options)); 2145 auto Options = (ppcg_options *)malloc(sizeof(ppcg_options)); 2146 2147 DebugOptions->dump_schedule_constraints = false; 2148 DebugOptions->dump_schedule = false; 2149 DebugOptions->dump_final_schedule = false; 2150 DebugOptions->dump_sizes = false; 2151 DebugOptions->verbose = false; 2152 2153 Options->debug = DebugOptions; 2154 2155 Options->group_chains = false; 2156 Options->reschedule = true; 2157 Options->scale_tile_loops = false; 2158 Options->wrap = false; 2159 2160 Options->non_negative_parameters = false; 2161 Options->ctx = nullptr; 2162 Options->sizes = nullptr; 2163 2164 Options->tile = true; 2165 Options->tile_size = 32; 2166 2167 Options->isolate_full_tiles = false; 2168 2169 Options->use_private_memory = PrivateMemory; 2170 Options->use_shared_memory = SharedMemory; 2171 Options->max_shared_memory = 48 * 1024; 2172 2173 Options->target = PPCG_TARGET_CUDA; 2174 Options->openmp = false; 2175 Options->linearize_device_arrays = true; 2176 Options->allow_gnu_extensions = false; 2177 2178 Options->unroll_copy_shared = false; 2179 Options->unroll_gpu_tile = false; 2180 Options->live_range_reordering = true; 2181 2182 Options->live_range_reordering = true; 2183 Options->hybrid = false; 2184 Options->opencl_compiler_options = nullptr; 2185 Options->opencl_use_gpu = false; 2186 Options->opencl_n_include_file = 0; 2187 Options->opencl_include_files = nullptr; 2188 Options->opencl_print_kernel_types = false; 2189 Options->opencl_embed_kernel_code = false; 2190 2191 Options->save_schedule_file = nullptr; 2192 Options->load_schedule_file = nullptr; 2193 2194 return Options; 2195 } 2196 2197 /// Get a tagged access relation containing all accesses of type @p AccessTy. 2198 /// 2199 /// Instead of a normal access of the form: 2200 /// 2201 /// Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)] 2202 /// 2203 /// a tagged access has the form 2204 /// 2205 /// [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)] 2206 /// 2207 /// where 'id' is an additional space that references the memory access that 2208 /// triggered the access. 2209 /// 2210 /// @param AccessTy The type of the memory accesses to collect. 2211 /// 2212 /// @return The relation describing all tagged memory accesses. 2213 isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) { 2214 isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace()); 2215 2216 for (auto &Stmt : *S) 2217 for (auto &Acc : Stmt) 2218 if (Acc->getType() == AccessTy) { 2219 isl_map *Relation = Acc->getAccessRelation(); 2220 Relation = isl_map_intersect_domain(Relation, Stmt.getDomain()); 2221 2222 isl_space *Space = isl_map_get_space(Relation); 2223 Space = isl_space_range(Space); 2224 Space = isl_space_from_range(Space); 2225 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2226 isl_map *Universe = isl_map_universe(Space); 2227 Relation = isl_map_domain_product(Relation, Universe); 2228 Accesses = isl_union_map_add_map(Accesses, Relation); 2229 } 2230 2231 return Accesses; 2232 } 2233 2234 /// Get the set of all read accesses, tagged with the access id. 2235 /// 2236 /// @see getTaggedAccesses 2237 isl_union_map *getTaggedReads() { 2238 return getTaggedAccesses(MemoryAccess::READ); 2239 } 2240 2241 /// Get the set of all may (and must) accesses, tagged with the access id. 2242 /// 2243 /// @see getTaggedAccesses 2244 isl_union_map *getTaggedMayWrites() { 2245 return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE), 2246 getTaggedAccesses(MemoryAccess::MUST_WRITE)); 2247 } 2248 2249 /// Get the set of all must accesses, tagged with the access id. 2250 /// 2251 /// @see getTaggedAccesses 2252 isl_union_map *getTaggedMustWrites() { 2253 return getTaggedAccesses(MemoryAccess::MUST_WRITE); 2254 } 2255 2256 /// Collect parameter and array names as isl_ids. 2257 /// 2258 /// To reason about the different parameters and arrays used, ppcg requires 2259 /// a list of all isl_ids in use. As PPCG traditionally performs 2260 /// source-to-source compilation each of these isl_ids is mapped to the 2261 /// expression that represents it. As we do not have a corresponding 2262 /// expression in Polly, we just map each id to a 'zero' expression to match 2263 /// the data format that ppcg expects. 2264 /// 2265 /// @returns Retun a map from collected ids to 'zero' ast expressions. 2266 __isl_give isl_id_to_ast_expr *getNames() { 2267 auto *Names = isl_id_to_ast_expr_alloc( 2268 S->getIslCtx(), 2269 S->getNumParams() + std::distance(S->array_begin(), S->array_end())); 2270 auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx())); 2271 auto *Space = S->getParamSpace(); 2272 2273 for (int I = 0, E = S->getNumParams(); I < E; ++I) { 2274 isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I); 2275 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2276 } 2277 2278 for (auto &Array : S->arrays()) { 2279 auto Id = Array->getBasePtrId(); 2280 Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero)); 2281 } 2282 2283 isl_space_free(Space); 2284 isl_ast_expr_free(Zero); 2285 2286 return Names; 2287 } 2288 2289 /// Create a new PPCG scop from the current scop. 2290 /// 2291 /// The PPCG scop is initialized with data from the current polly::Scop. From 2292 /// this initial data, the data-dependences in the PPCG scop are initialized. 2293 /// We do not use Polly's dependence analysis for now, to ensure we match 2294 /// the PPCG default behaviour more closely. 2295 /// 2296 /// @returns A new ppcg scop. 2297 ppcg_scop *createPPCGScop() { 2298 MustKillsInfo KillsInfo = computeMustKillsInfo(*S); 2299 2300 auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop)); 2301 2302 PPCGScop->options = createPPCGOptions(); 2303 // enable live range reordering 2304 PPCGScop->options->live_range_reordering = 1; 2305 2306 PPCGScop->start = 0; 2307 PPCGScop->end = 0; 2308 2309 PPCGScop->context = S->getContext(); 2310 PPCGScop->domain = S->getDomains(); 2311 // TODO: investigate this further. PPCG calls collect_call_domains. 2312 PPCGScop->call = isl_union_set_from_set(S->getContext()); 2313 PPCGScop->tagged_reads = getTaggedReads(); 2314 PPCGScop->reads = S->getReads(); 2315 PPCGScop->live_in = nullptr; 2316 PPCGScop->tagged_may_writes = getTaggedMayWrites(); 2317 PPCGScop->may_writes = S->getWrites(); 2318 PPCGScop->tagged_must_writes = getTaggedMustWrites(); 2319 PPCGScop->must_writes = S->getMustWrites(); 2320 PPCGScop->live_out = nullptr; 2321 PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take(); 2322 PPCGScop->must_kills = KillsInfo.MustKills.take(); 2323 2324 PPCGScop->tagger = nullptr; 2325 PPCGScop->independence = 2326 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2327 PPCGScop->dep_flow = nullptr; 2328 PPCGScop->tagged_dep_flow = nullptr; 2329 PPCGScop->dep_false = nullptr; 2330 PPCGScop->dep_forced = nullptr; 2331 PPCGScop->dep_order = nullptr; 2332 PPCGScop->tagged_dep_order = nullptr; 2333 2334 PPCGScop->schedule = S->getScheduleTree(); 2335 // If we have something non-trivial to kill, add it to the schedule 2336 if (KillsInfo.KillsSchedule.get()) 2337 PPCGScop->schedule = isl_schedule_sequence( 2338 PPCGScop->schedule, KillsInfo.KillsSchedule.take()); 2339 2340 PPCGScop->names = getNames(); 2341 PPCGScop->pet = nullptr; 2342 2343 compute_tagger(PPCGScop); 2344 compute_dependences(PPCGScop); 2345 eliminate_dead_code(PPCGScop); 2346 2347 return PPCGScop; 2348 } 2349 2350 /// Collect the array accesses in a statement. 2351 /// 2352 /// @param Stmt The statement for which to collect the accesses. 2353 /// 2354 /// @returns A list of array accesses. 2355 gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) { 2356 gpu_stmt_access *Accesses = nullptr; 2357 2358 for (MemoryAccess *Acc : Stmt) { 2359 auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access); 2360 Access->read = Acc->isRead(); 2361 Access->write = Acc->isWrite(); 2362 Access->access = Acc->getAccessRelation(); 2363 isl_space *Space = isl_map_get_space(Access->access); 2364 Space = isl_space_range(Space); 2365 Space = isl_space_from_range(Space); 2366 Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId()); 2367 isl_map *Universe = isl_map_universe(Space); 2368 Access->tagged_access = 2369 isl_map_domain_product(Acc->getAccessRelation(), Universe); 2370 Access->exact_write = !Acc->isMayWrite(); 2371 Access->ref_id = Acc->getId(); 2372 Access->next = Accesses; 2373 Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions(); 2374 Accesses = Access; 2375 } 2376 2377 return Accesses; 2378 } 2379 2380 /// Collect the list of GPU statements. 2381 /// 2382 /// Each statement has an id, a pointer to the underlying data structure, 2383 /// as well as a list with all memory accesses. 2384 /// 2385 /// TODO: Initialize the list of memory accesses. 2386 /// 2387 /// @returns A linked-list of statements. 2388 gpu_stmt *getStatements() { 2389 gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt, 2390 std::distance(S->begin(), S->end())); 2391 2392 int i = 0; 2393 for (auto &Stmt : *S) { 2394 gpu_stmt *GPUStmt = &Stmts[i]; 2395 2396 GPUStmt->id = Stmt.getDomainId(); 2397 2398 // We use the pet stmt pointer to keep track of the Polly statements. 2399 GPUStmt->stmt = (pet_stmt *)&Stmt; 2400 GPUStmt->accesses = getStmtAccesses(Stmt); 2401 i++; 2402 } 2403 2404 return Stmts; 2405 } 2406 2407 /// Derive the extent of an array. 2408 /// 2409 /// The extent of an array is the set of elements that are within the 2410 /// accessed array. For the inner dimensions, the extent constraints are 2411 /// 0 and the size of the corresponding array dimension. For the first 2412 /// (outermost) dimension, the extent constraints are the minimal and maximal 2413 /// subscript value for the first dimension. 2414 /// 2415 /// @param Array The array to derive the extent for. 2416 /// 2417 /// @returns An isl_set describing the extent of the array. 2418 __isl_give isl_set *getExtent(ScopArrayInfo *Array) { 2419 unsigned NumDims = Array->getNumberOfDimensions(); 2420 isl_union_map *Accesses = S->getAccesses(); 2421 Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains()); 2422 Accesses = isl_union_map_detect_equalities(Accesses); 2423 isl_union_set *AccessUSet = isl_union_map_range(Accesses); 2424 AccessUSet = isl_union_set_coalesce(AccessUSet); 2425 AccessUSet = isl_union_set_detect_equalities(AccessUSet); 2426 AccessUSet = isl_union_set_coalesce(AccessUSet); 2427 2428 if (isl_union_set_is_empty(AccessUSet)) { 2429 isl_union_set_free(AccessUSet); 2430 return isl_set_empty(Array->getSpace()); 2431 } 2432 2433 if (Array->getNumberOfDimensions() == 0) { 2434 isl_union_set_free(AccessUSet); 2435 return isl_set_universe(Array->getSpace()); 2436 } 2437 2438 isl_set *AccessSet = 2439 isl_union_set_extract_set(AccessUSet, Array->getSpace()); 2440 2441 isl_union_set_free(AccessUSet); 2442 isl_local_space *LS = isl_local_space_from_space(Array->getSpace()); 2443 2444 isl_pw_aff *Val = 2445 isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0)); 2446 2447 isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0); 2448 isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0); 2449 OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in, 2450 isl_pw_aff_dim(Val, isl_dim_in)); 2451 OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in, 2452 isl_pw_aff_dim(Val, isl_dim_in)); 2453 OuterMin = 2454 isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId()); 2455 OuterMax = 2456 isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId()); 2457 2458 isl_set *Extent = isl_set_universe(Array->getSpace()); 2459 2460 Extent = isl_set_intersect( 2461 Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val))); 2462 Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val)); 2463 2464 for (unsigned i = 1; i < NumDims; ++i) 2465 Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0); 2466 2467 for (unsigned i = 0; i < NumDims; ++i) { 2468 isl_pw_aff *PwAff = 2469 const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i)); 2470 2471 // isl_pw_aff can be NULL for zero dimension. Only in the case of a 2472 // Fortran array will we have a legitimate dimension. 2473 if (!PwAff) { 2474 assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension"); 2475 continue; 2476 } 2477 2478 isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain( 2479 isl_local_space_from_space(Array->getSpace()), isl_dim_set, i)); 2480 PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in, 2481 isl_pw_aff_dim(Val, isl_dim_in)); 2482 PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in, 2483 isl_pw_aff_get_tuple_id(Val, isl_dim_in)); 2484 auto *Set = isl_pw_aff_gt_set(PwAff, Val); 2485 Extent = isl_set_intersect(Set, Extent); 2486 } 2487 2488 return Extent; 2489 } 2490 2491 /// Derive the bounds of an array. 2492 /// 2493 /// For the first dimension we derive the bound of the array from the extent 2494 /// of this dimension. For inner dimensions we obtain their size directly from 2495 /// ScopArrayInfo. 2496 /// 2497 /// @param PPCGArray The array to compute bounds for. 2498 /// @param Array The polly array from which to take the information. 2499 void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) { 2500 isl_pw_aff_list *BoundsList = 2501 isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index); 2502 std::vector<isl::pw_aff> PwAffs; 2503 2504 isl_space *AlignSpace = S->getParamSpace(); 2505 AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1); 2506 2507 if (PPCGArray.n_index > 0) { 2508 if (isl_set_is_empty(PPCGArray.extent)) { 2509 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2510 isl_local_space *LS = isl_local_space_from_space( 2511 isl_space_params(isl_set_get_space(Dom))); 2512 isl_set_free(Dom); 2513 isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS)); 2514 Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace)); 2515 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero))); 2516 BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero); 2517 } else { 2518 isl_set *Dom = isl_set_copy(PPCGArray.extent); 2519 Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1); 2520 isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0); 2521 isl_set_free(Dom); 2522 Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound)); 2523 isl_local_space *LS = 2524 isl_local_space_from_space(isl_set_get_space(Dom)); 2525 isl_aff *One = isl_aff_zero_on_domain(LS); 2526 One = isl_aff_add_constant_si(One, 1); 2527 Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One)); 2528 Bound = isl_pw_aff_gist(Bound, S->getContext()); 2529 Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 2530 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 2531 BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound); 2532 } 2533 } 2534 2535 for (unsigned i = 1; i < PPCGArray.n_index; ++i) { 2536 isl_pw_aff *Bound = Array->getDimensionSizePw(i); 2537 auto LS = isl_pw_aff_get_domain_space(Bound); 2538 auto Aff = isl_multi_aff_zero(LS); 2539 Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff); 2540 Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace)); 2541 PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound))); 2542 BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound); 2543 } 2544 2545 isl_space_free(AlignSpace); 2546 isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent); 2547 2548 assert(BoundsSpace && "Unable to access space of array."); 2549 assert(BoundsList && "Unable to access list of bounds."); 2550 2551 PPCGArray.bound = 2552 isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList); 2553 assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly."); 2554 } 2555 2556 /// Create the arrays for @p PPCGProg. 2557 /// 2558 /// @param PPCGProg The program to compute the arrays for. 2559 void createArrays(gpu_prog *PPCGProg) { 2560 int i = 0; 2561 for (auto &Array : S->arrays()) { 2562 std::string TypeName; 2563 raw_string_ostream OS(TypeName); 2564 2565 OS << *Array->getElementType(); 2566 TypeName = OS.str(); 2567 2568 gpu_array_info &PPCGArray = PPCGProg->array[i]; 2569 2570 PPCGArray.space = Array->getSpace(); 2571 PPCGArray.type = strdup(TypeName.c_str()); 2572 PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8; 2573 PPCGArray.name = strdup(Array->getName().c_str()); 2574 PPCGArray.extent = nullptr; 2575 PPCGArray.n_index = Array->getNumberOfDimensions(); 2576 PPCGArray.extent = getExtent(Array); 2577 PPCGArray.n_ref = 0; 2578 PPCGArray.refs = nullptr; 2579 PPCGArray.accessed = true; 2580 PPCGArray.read_only_scalar = 2581 Array->isReadOnly() && Array->getNumberOfDimensions() == 0; 2582 PPCGArray.has_compound_element = false; 2583 PPCGArray.local = false; 2584 PPCGArray.declare_local = false; 2585 PPCGArray.global = false; 2586 PPCGArray.linearize = false; 2587 PPCGArray.dep_order = nullptr; 2588 PPCGArray.user = Array; 2589 2590 PPCGArray.bound = nullptr; 2591 setArrayBounds(PPCGArray, Array); 2592 i++; 2593 2594 collect_references(PPCGProg, &PPCGArray); 2595 } 2596 } 2597 2598 /// Create an identity map between the arrays in the scop. 2599 /// 2600 /// @returns An identity map between the arrays in the scop. 2601 isl_union_map *getArrayIdentity() { 2602 isl_union_map *Maps = isl_union_map_empty(S->getParamSpace()); 2603 2604 for (auto &Array : S->arrays()) { 2605 isl_space *Space = Array->getSpace(); 2606 Space = isl_space_map_from_set(Space); 2607 isl_map *Identity = isl_map_identity(Space); 2608 Maps = isl_union_map_add_map(Maps, Identity); 2609 } 2610 2611 return Maps; 2612 } 2613 2614 /// Create a default-initialized PPCG GPU program. 2615 /// 2616 /// @returns A new gpu program description. 2617 gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) { 2618 2619 if (!PPCGScop) 2620 return nullptr; 2621 2622 auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog); 2623 2624 PPCGProg->ctx = S->getIslCtx(); 2625 PPCGProg->scop = PPCGScop; 2626 PPCGProg->context = isl_set_copy(PPCGScop->context); 2627 PPCGProg->read = isl_union_map_copy(PPCGScop->reads); 2628 PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes); 2629 PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes); 2630 PPCGProg->tagged_must_kill = 2631 isl_union_map_copy(PPCGScop->tagged_must_kills); 2632 PPCGProg->to_inner = getArrayIdentity(); 2633 PPCGProg->to_outer = getArrayIdentity(); 2634 // TODO: verify that this assignment is correct. 2635 PPCGProg->any_to_outer = nullptr; 2636 2637 // this needs to be set when live range reordering is enabled. 2638 // NOTE: I believe that is conservatively correct. I'm not sure 2639 // what the semantics of this is. 2640 // Quoting PPCG/gpu.h: "Order dependences on non-scalars." 2641 PPCGProg->array_order = 2642 isl_union_map_empty(isl_set_get_space(PPCGScop->context)); 2643 PPCGProg->n_stmts = std::distance(S->begin(), S->end()); 2644 PPCGProg->stmts = getStatements(); 2645 PPCGProg->n_array = std::distance(S->array_begin(), S->array_end()); 2646 PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info, 2647 PPCGProg->n_array); 2648 2649 createArrays(PPCGProg); 2650 2651 PPCGProg->may_persist = compute_may_persist(PPCGProg); 2652 return PPCGProg; 2653 } 2654 2655 struct PrintGPUUserData { 2656 struct cuda_info *CudaInfo; 2657 struct gpu_prog *PPCGProg; 2658 std::vector<ppcg_kernel *> Kernels; 2659 }; 2660 2661 /// Print a user statement node in the host code. 2662 /// 2663 /// We use ppcg's printing facilities to print the actual statement and 2664 /// additionally build up a list of all kernels that are encountered in the 2665 /// host ast. 2666 /// 2667 /// @param P The printer to print to 2668 /// @param Options The printing options to use 2669 /// @param Node The node to print 2670 /// @param User A user pointer to carry additional data. This pointer is 2671 /// expected to be of type PrintGPUUserData. 2672 /// 2673 /// @returns A printer to which the output has been printed. 2674 static __isl_give isl_printer * 2675 printHostUser(__isl_take isl_printer *P, 2676 __isl_take isl_ast_print_options *Options, 2677 __isl_take isl_ast_node *Node, void *User) { 2678 auto Data = (struct PrintGPUUserData *)User; 2679 auto Id = isl_ast_node_get_annotation(Node); 2680 2681 if (Id) { 2682 bool IsUser = !strcmp(isl_id_get_name(Id), "user"); 2683 2684 // If this is a user statement, format it ourselves as ppcg would 2685 // otherwise try to call pet functionality that is not available in 2686 // Polly. 2687 if (IsUser) { 2688 P = isl_printer_start_line(P); 2689 P = isl_printer_print_ast_node(P, Node); 2690 P = isl_printer_end_line(P); 2691 isl_id_free(Id); 2692 isl_ast_print_options_free(Options); 2693 return P; 2694 } 2695 2696 auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id); 2697 isl_id_free(Id); 2698 Data->Kernels.push_back(Kernel); 2699 } 2700 2701 return print_host_user(P, Options, Node, User); 2702 } 2703 2704 /// Print C code corresponding to the control flow in @p Kernel. 2705 /// 2706 /// @param Kernel The kernel to print 2707 void printKernel(ppcg_kernel *Kernel) { 2708 auto *P = isl_printer_to_str(S->getIslCtx()); 2709 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2710 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2711 P = isl_ast_node_print(Kernel->tree, P, Options); 2712 char *String = isl_printer_get_str(P); 2713 printf("%s\n", String); 2714 free(String); 2715 isl_printer_free(P); 2716 } 2717 2718 /// Print C code corresponding to the GPU code described by @p Tree. 2719 /// 2720 /// @param Tree An AST describing GPU code 2721 /// @param PPCGProg The PPCG program from which @Tree has been constructed. 2722 void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) { 2723 auto *P = isl_printer_to_str(S->getIslCtx()); 2724 P = isl_printer_set_output_format(P, ISL_FORMAT_C); 2725 2726 PrintGPUUserData Data; 2727 Data.PPCGProg = PPCGProg; 2728 2729 auto *Options = isl_ast_print_options_alloc(S->getIslCtx()); 2730 Options = 2731 isl_ast_print_options_set_print_user(Options, printHostUser, &Data); 2732 P = isl_ast_node_print(Tree, P, Options); 2733 char *String = isl_printer_get_str(P); 2734 printf("# host\n"); 2735 printf("%s\n", String); 2736 free(String); 2737 isl_printer_free(P); 2738 2739 for (auto Kernel : Data.Kernels) { 2740 printf("# kernel%d\n", Kernel->id); 2741 printKernel(Kernel); 2742 } 2743 } 2744 2745 // Generate a GPU program using PPCG. 2746 // 2747 // GPU mapping consists of multiple steps: 2748 // 2749 // 1) Compute new schedule for the program. 2750 // 2) Map schedule to GPU (TODO) 2751 // 3) Generate code for new schedule (TODO) 2752 // 2753 // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer 2754 // is mostly CPU specific. Instead, we use PPCG's GPU code generation 2755 // strategy directly from this pass. 2756 gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) { 2757 2758 auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen); 2759 2760 PPCGGen->ctx = S->getIslCtx(); 2761 PPCGGen->options = PPCGScop->options; 2762 PPCGGen->print = nullptr; 2763 PPCGGen->print_user = nullptr; 2764 PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt; 2765 PPCGGen->prog = PPCGProg; 2766 PPCGGen->tree = nullptr; 2767 PPCGGen->types.n = 0; 2768 PPCGGen->types.name = nullptr; 2769 PPCGGen->sizes = nullptr; 2770 PPCGGen->used_sizes = nullptr; 2771 PPCGGen->kernel_id = 0; 2772 2773 // Set scheduling strategy to same strategy PPCG is using. 2774 isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true); 2775 isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true); 2776 isl_options_set_schedule_whole_component(PPCGGen->ctx, false); 2777 2778 isl_schedule *Schedule = get_schedule(PPCGGen); 2779 2780 int has_permutable = has_any_permutable_node(Schedule); 2781 2782 if (!has_permutable || has_permutable < 0) { 2783 Schedule = isl_schedule_free(Schedule); 2784 } else { 2785 Schedule = map_to_device(PPCGGen, Schedule); 2786 PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule)); 2787 } 2788 2789 if (DumpSchedule) { 2790 isl_printer *P = isl_printer_to_str(S->getIslCtx()); 2791 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK); 2792 P = isl_printer_print_str(P, "Schedule\n"); 2793 P = isl_printer_print_str(P, "========\n"); 2794 if (Schedule) 2795 P = isl_printer_print_schedule(P, Schedule); 2796 else 2797 P = isl_printer_print_str(P, "No schedule found\n"); 2798 2799 printf("%s\n", isl_printer_get_str(P)); 2800 isl_printer_free(P); 2801 } 2802 2803 if (DumpCode) { 2804 printf("Code\n"); 2805 printf("====\n"); 2806 if (PPCGGen->tree) 2807 printGPUTree(PPCGGen->tree, PPCGProg); 2808 else 2809 printf("No code generated\n"); 2810 } 2811 2812 isl_schedule_free(Schedule); 2813 2814 return PPCGGen; 2815 } 2816 2817 /// Free gpu_gen structure. 2818 /// 2819 /// @param PPCGGen The ppcg_gen object to free. 2820 void freePPCGGen(gpu_gen *PPCGGen) { 2821 isl_ast_node_free(PPCGGen->tree); 2822 isl_union_map_free(PPCGGen->sizes); 2823 isl_union_map_free(PPCGGen->used_sizes); 2824 free(PPCGGen); 2825 } 2826 2827 /// Free the options in the ppcg scop structure. 2828 /// 2829 /// ppcg is not freeing these options for us. To avoid leaks we do this 2830 /// ourselves. 2831 /// 2832 /// @param PPCGScop The scop referencing the options to free. 2833 void freeOptions(ppcg_scop *PPCGScop) { 2834 free(PPCGScop->options->debug); 2835 PPCGScop->options->debug = nullptr; 2836 free(PPCGScop->options); 2837 PPCGScop->options = nullptr; 2838 } 2839 2840 /// Approximate the number of points in the set. 2841 /// 2842 /// This function returns an ast expression that overapproximates the number 2843 /// of points in an isl set through the rectangular hull surrounding this set. 2844 /// 2845 /// @param Set The set to count. 2846 /// @param Build The isl ast build object to use for creating the ast 2847 /// expression. 2848 /// 2849 /// @returns An approximation of the number of points in the set. 2850 __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set, 2851 __isl_keep isl_ast_build *Build) { 2852 2853 isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1); 2854 auto *Expr = isl_ast_expr_from_val(isl_val_copy(One)); 2855 2856 isl_space *Space = isl_set_get_space(Set); 2857 Space = isl_space_params(Space); 2858 auto *Univ = isl_set_universe(Space); 2859 isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One); 2860 2861 for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) { 2862 isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i); 2863 isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i); 2864 isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min); 2865 DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff)); 2866 auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize); 2867 Expr = isl_ast_expr_mul(Expr, DimSizeExpr); 2868 } 2869 2870 isl_set_free(Set); 2871 isl_pw_aff_free(OneAff); 2872 2873 return Expr; 2874 } 2875 2876 /// Approximate a number of dynamic instructions executed by a given 2877 /// statement. 2878 /// 2879 /// @param Stmt The statement for which to compute the number of dynamic 2880 /// instructions. 2881 /// @param Build The isl ast build object to use for creating the ast 2882 /// expression. 2883 /// @returns An approximation of the number of dynamic instructions executed 2884 /// by @p Stmt. 2885 __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt, 2886 __isl_keep isl_ast_build *Build) { 2887 auto Iterations = approxPointsInSet(Stmt.getDomain(), Build); 2888 2889 long InstCount = 0; 2890 2891 if (Stmt.isBlockStmt()) { 2892 auto *BB = Stmt.getBasicBlock(); 2893 InstCount = std::distance(BB->begin(), BB->end()); 2894 } else { 2895 auto *R = Stmt.getRegion(); 2896 2897 for (auto *BB : R->blocks()) { 2898 InstCount += std::distance(BB->begin(), BB->end()); 2899 } 2900 } 2901 2902 isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount); 2903 auto *InstExpr = isl_ast_expr_from_val(InstVal); 2904 return isl_ast_expr_mul(InstExpr, Iterations); 2905 } 2906 2907 /// Approximate dynamic instructions executed in scop. 2908 /// 2909 /// @param S The scop for which to approximate dynamic instructions. 2910 /// @param Build The isl ast build object to use for creating the ast 2911 /// expression. 2912 /// @returns An approximation of the number of dynamic instructions executed 2913 /// in @p S. 2914 __isl_give isl_ast_expr * 2915 getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) { 2916 isl_ast_expr *Instructions; 2917 2918 isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0); 2919 Instructions = isl_ast_expr_from_val(Zero); 2920 2921 for (ScopStmt &Stmt : S) { 2922 isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build); 2923 Instructions = isl_ast_expr_add(Instructions, StmtInstructions); 2924 } 2925 return Instructions; 2926 } 2927 2928 /// Create a check that ensures sufficient compute in scop. 2929 /// 2930 /// @param S The scop for which to ensure sufficient compute. 2931 /// @param Build The isl ast build object to use for creating the ast 2932 /// expression. 2933 /// @returns An expression that evaluates to TRUE in case of sufficient 2934 /// compute and to FALSE, otherwise. 2935 __isl_give isl_ast_expr * 2936 createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) { 2937 auto Iterations = getNumberOfIterations(S, Build); 2938 auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute); 2939 auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal); 2940 return isl_ast_expr_ge(Iterations, MinComputeExpr); 2941 } 2942 2943 /// Check if the basic block contains a function we cannot codegen for GPU 2944 /// kernels. 2945 /// 2946 /// If this basic block does something with a `Function` other than calling 2947 /// a function that we support in a kernel, return true. 2948 bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) { 2949 for (const Instruction &Inst : *BB) { 2950 const CallInst *Call = dyn_cast<CallInst>(&Inst); 2951 if (Call && isValidFunctionInKernel(Call->getCalledFunction())) { 2952 continue; 2953 } 2954 2955 for (Value *SrcVal : Inst.operands()) { 2956 PointerType *p = dyn_cast<PointerType>(SrcVal->getType()); 2957 if (!p) 2958 continue; 2959 if (isa<FunctionType>(p->getElementType())) 2960 return true; 2961 } 2962 } 2963 return false; 2964 } 2965 2966 /// Return whether the Scop S uses functions in a way that we do not support. 2967 bool containsInvalidKernelFunction(const Scop &S) { 2968 for (auto &Stmt : S) { 2969 if (Stmt.isBlockStmt()) { 2970 if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock())) 2971 return true; 2972 } else { 2973 assert(Stmt.isRegionStmt() && 2974 "Stmt was neither block nor region statement"); 2975 for (const BasicBlock *BB : Stmt.getRegion()->blocks()) 2976 if (containsInvalidKernelFunctionInBlock(BB)) 2977 return true; 2978 } 2979 } 2980 return false; 2981 } 2982 2983 /// Generate code for a given GPU AST described by @p Root. 2984 /// 2985 /// @param Root An isl_ast_node pointing to the root of the GPU AST. 2986 /// @param Prog The GPU Program to generate code for. 2987 void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) { 2988 ScopAnnotator Annotator; 2989 Annotator.buildAliasScopes(*S); 2990 2991 Region *R = &S->getRegion(); 2992 2993 simplifyRegion(R, DT, LI, RI); 2994 2995 BasicBlock *EnteringBB = R->getEnteringBlock(); 2996 2997 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 2998 2999 // Only build the run-time condition and parameters _after_ having 3000 // introduced the conditional branch. This is important as the conditional 3001 // branch will guard the original scop from new induction variables that 3002 // the SCEVExpander may introduce while code generating the parameters and 3003 // which may introduce scalar dependences that prevent us from correctly 3004 // code generating this scop. 3005 BBPair StartExitBlocks; 3006 BranchInst *CondBr = nullptr; 3007 std::tie(StartExitBlocks, CondBr) = 3008 executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI); 3009 BasicBlock *StartBlock = std::get<0>(StartExitBlocks); 3010 3011 assert(CondBr && "CondBr not initialized by executeScopConditionally"); 3012 3013 GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S, 3014 StartBlock, Prog, Runtime, Architecture); 3015 3016 // TODO: Handle LICM 3017 auto SplitBlock = StartBlock->getSinglePredecessor(); 3018 Builder.SetInsertPoint(SplitBlock->getTerminator()); 3019 NodeBuilder.addParameters(S->getContext()); 3020 3021 isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx()); 3022 isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build); 3023 isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build); 3024 Condition = isl_ast_expr_and(Condition, SufficientCompute); 3025 isl_ast_build_free(Build); 3026 3027 // preload invariant loads. Note: This should happen before the RTC 3028 // because the RTC may depend on values that are invariant load hoisted. 3029 NodeBuilder.preloadInvariantLoads(); 3030 3031 Value *RTC = NodeBuilder.createRTC(Condition); 3032 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 3033 3034 Builder.SetInsertPoint(&*StartBlock->begin()); 3035 3036 NodeBuilder.create(Root); 3037 3038 /// In case a sequential kernel has more surrounding loops as any parallel 3039 /// kernel, the SCoP is probably mostly sequential. Hence, there is no 3040 /// point in running it on a GPU. 3041 if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel) 3042 CondBr->setOperand(0, Builder.getFalse()); 3043 3044 if (!NodeBuilder.BuildSuccessful) 3045 CondBr->setOperand(0, Builder.getFalse()); 3046 } 3047 3048 bool runOnScop(Scop &CurrentScop) override { 3049 S = &CurrentScop; 3050 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3051 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3052 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 3053 DL = &S->getRegion().getEntry()->getModule()->getDataLayout(); 3054 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 3055 3056 // We currently do not support functions other than intrinsics inside 3057 // kernels, as code generation will need to offload function calls to the 3058 // kernel. This may lead to a kernel trying to call a function on the host. 3059 // This also allows us to prevent codegen from trying to take the 3060 // address of an intrinsic function to send to the kernel. 3061 if (containsInvalidKernelFunction(CurrentScop)) { 3062 DEBUG( 3063 dbgs() 3064 << "Scop contains function which cannot be materialised in a GPU " 3065 "kernel. Bailing out.\n";); 3066 return false; 3067 } 3068 3069 auto PPCGScop = createPPCGScop(); 3070 auto PPCGProg = createPPCGProg(PPCGScop); 3071 auto PPCGGen = generateGPU(PPCGScop, PPCGProg); 3072 3073 if (PPCGGen->tree) { 3074 generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg); 3075 CurrentScop.markAsToBeSkipped(); 3076 } 3077 3078 freeOptions(PPCGScop); 3079 freePPCGGen(PPCGGen); 3080 gpu_prog_free(PPCGProg); 3081 ppcg_scop_free(PPCGScop); 3082 3083 return true; 3084 } 3085 3086 void printScop(raw_ostream &, Scop &) const override {} 3087 3088 void getAnalysisUsage(AnalysisUsage &AU) const override { 3089 AU.addRequired<DominatorTreeWrapperPass>(); 3090 AU.addRequired<RegionInfoPass>(); 3091 AU.addRequired<ScalarEvolutionWrapperPass>(); 3092 AU.addRequired<ScopDetectionWrapperPass>(); 3093 AU.addRequired<ScopInfoRegionPass>(); 3094 AU.addRequired<LoopInfoWrapperPass>(); 3095 3096 AU.addPreserved<AAResultsWrapperPass>(); 3097 AU.addPreserved<BasicAAWrapperPass>(); 3098 AU.addPreserved<LoopInfoWrapperPass>(); 3099 AU.addPreserved<DominatorTreeWrapperPass>(); 3100 AU.addPreserved<GlobalsAAWrapperPass>(); 3101 AU.addPreserved<ScopDetectionWrapperPass>(); 3102 AU.addPreserved<ScalarEvolutionWrapperPass>(); 3103 AU.addPreserved<SCEVAAWrapperPass>(); 3104 3105 // FIXME: We do not yet add regions for the newly generated code to the 3106 // region tree. 3107 AU.addPreserved<RegionInfoPass>(); 3108 AU.addPreserved<ScopInfoRegionPass>(); 3109 } 3110 }; 3111 } // namespace 3112 3113 char PPCGCodeGeneration::ID = 1; 3114 3115 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) { 3116 PPCGCodeGeneration *generator = new PPCGCodeGeneration(); 3117 generator->Runtime = Runtime; 3118 generator->Architecture = Arch; 3119 return generator; 3120 } 3121 3122 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg", 3123 "Polly - Apply PPCG translation to SCOP", false, false) 3124 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 3125 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 3126 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 3127 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 3128 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 3129 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass); 3130 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg", 3131 "Polly - Apply PPCG translation to SCOP", false, false) 3132