1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This provides a class for OpenMP runtime code generation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 14 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 15 16 #include "CGValue.h" 17 #include "clang/AST/DeclOpenMP.h" 18 #include "clang/AST/GlobalDecl.h" 19 #include "clang/AST/Type.h" 20 #include "clang/Basic/OpenMPKinds.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/StringMap.h" 26 #include "llvm/ADT/StringSet.h" 27 #include "llvm/Frontend/OpenMP/OMPConstants.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/ValueHandle.h" 30 #include "llvm/Support/AtomicOrdering.h" 31 32 namespace llvm { 33 class ArrayType; 34 class Constant; 35 class FunctionType; 36 class GlobalVariable; 37 class StructType; 38 class Type; 39 class Value; 40 } // namespace llvm 41 42 namespace clang { 43 class Expr; 44 class OMPDependClause; 45 class OMPExecutableDirective; 46 class OMPLoopDirective; 47 class VarDecl; 48 class OMPDeclareReductionDecl; 49 class IdentifierInfo; 50 51 namespace CodeGen { 52 class Address; 53 class CodeGenFunction; 54 class CodeGenModule; 55 56 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP 57 /// region. 58 class PrePostActionTy { 59 public: 60 explicit PrePostActionTy() {} 61 virtual void Enter(CodeGenFunction &CGF) {} 62 virtual void Exit(CodeGenFunction &CGF) {} 63 virtual ~PrePostActionTy() {} 64 }; 65 66 /// Class provides a way to call simple version of codegen for OpenMP region, or 67 /// an advanced with possible pre|post-actions in codegen. 68 class RegionCodeGenTy final { 69 intptr_t CodeGen; 70 typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); 71 CodeGenTy Callback; 72 mutable PrePostActionTy *PrePostAction; 73 RegionCodeGenTy() = delete; 74 RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete; 75 template <typename Callable> 76 static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, 77 PrePostActionTy &Action) { 78 return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); 79 } 80 81 public: 82 template <typename Callable> 83 RegionCodeGenTy( 84 Callable &&CodeGen, 85 std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>, 86 RegionCodeGenTy>::value> * = nullptr) 87 : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), 88 Callback(CallbackFn<std::remove_reference_t<Callable>>), 89 PrePostAction(nullptr) {} 90 void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } 91 void operator()(CodeGenFunction &CGF) const; 92 }; 93 94 struct OMPTaskDataTy final { 95 SmallVector<const Expr *, 4> PrivateVars; 96 SmallVector<const Expr *, 4> PrivateCopies; 97 SmallVector<const Expr *, 4> FirstprivateVars; 98 SmallVector<const Expr *, 4> FirstprivateCopies; 99 SmallVector<const Expr *, 4> FirstprivateInits; 100 SmallVector<const Expr *, 4> LastprivateVars; 101 SmallVector<const Expr *, 4> LastprivateCopies; 102 SmallVector<const Expr *, 4> ReductionVars; 103 SmallVector<const Expr *, 4> ReductionOrigs; 104 SmallVector<const Expr *, 4> ReductionCopies; 105 SmallVector<const Expr *, 4> ReductionOps; 106 struct DependData { 107 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; 108 const Expr *IteratorExpr = nullptr; 109 SmallVector<const Expr *, 4> DepExprs; 110 explicit DependData() = default; 111 DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr) 112 : DepKind(DepKind), IteratorExpr(IteratorExpr) {} 113 }; 114 SmallVector<DependData, 4> Dependences; 115 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 116 llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; 117 llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; 118 llvm::Value *Reductions = nullptr; 119 unsigned NumberOfParts = 0; 120 bool Tied = true; 121 bool Nogroup = false; 122 bool IsReductionWithTaskMod = false; 123 bool IsWorksharingReduction = false; 124 }; 125 126 /// Class intended to support codegen of all kind of the reduction clauses. 127 class ReductionCodeGen { 128 private: 129 /// Data required for codegen of reduction clauses. 130 struct ReductionData { 131 /// Reference to the item shared between tasks to reduce into. 132 const Expr *Shared = nullptr; 133 /// Reference to the original item. 134 const Expr *Ref = nullptr; 135 /// Helper expression for generation of private copy. 136 const Expr *Private = nullptr; 137 /// Helper expression for generation reduction operation. 138 const Expr *ReductionOp = nullptr; 139 ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private, 140 const Expr *ReductionOp) 141 : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) { 142 } 143 }; 144 /// List of reduction-based clauses. 145 SmallVector<ReductionData, 4> ClausesData; 146 147 /// List of addresses of shared variables/expressions. 148 SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; 149 /// List of addresses of original variables/expressions. 150 SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses; 151 /// Sizes of the reduction items in chars. 152 SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; 153 /// Base declarations for the reduction items. 154 SmallVector<const VarDecl *, 4> BaseDecls; 155 156 /// Emits lvalue for shared expression. 157 LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); 158 /// Emits upper bound for shared expression (if array section). 159 LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); 160 /// Performs aggregate initialization. 161 /// \param N Number of reduction item in the common list. 162 /// \param PrivateAddr Address of the corresponding private item. 163 /// \param SharedLVal Address of the original shared variable. 164 /// \param DRD Declare reduction construct used for reduction item. 165 void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, 166 Address PrivateAddr, LValue SharedLVal, 167 const OMPDeclareReductionDecl *DRD); 168 169 public: 170 ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs, 171 ArrayRef<const Expr *> Privates, 172 ArrayRef<const Expr *> ReductionOps); 173 /// Emits lvalue for the shared and original reduction item. 174 /// \param N Number of the reduction item. 175 void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N); 176 /// Emits the code for the variable-modified type, if required. 177 /// \param N Number of the reduction item. 178 void emitAggregateType(CodeGenFunction &CGF, unsigned N); 179 /// Emits the code for the variable-modified type, if required. 180 /// \param N Number of the reduction item. 181 /// \param Size Size of the type in chars. 182 void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); 183 /// Performs initialization of the private copy for the reduction item. 184 /// \param N Number of the reduction item. 185 /// \param PrivateAddr Address of the corresponding private item. 186 /// \param DefaultInit Default initialization sequence that should be 187 /// performed if no reduction specific initialization is found. 188 /// \param SharedLVal Address of the original shared variable. 189 void 190 emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, 191 LValue SharedLVal, 192 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); 193 /// Returns true if the private copy requires cleanups. 194 bool needCleanups(unsigned N); 195 /// Emits cleanup code for the reduction item. 196 /// \param N Number of the reduction item. 197 /// \param PrivateAddr Address of the corresponding private item. 198 void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); 199 /// Adjusts \p PrivatedAddr for using instead of the original variable 200 /// address in normal operations. 201 /// \param N Number of the reduction item. 202 /// \param PrivateAddr Address of the corresponding private item. 203 Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, 204 Address PrivateAddr); 205 /// Returns LValue for the reduction item. 206 LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } 207 /// Returns LValue for the original reduction item. 208 LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; } 209 /// Returns the size of the reduction item (in chars and total number of 210 /// elements in the item), or nullptr, if the size is a constant. 211 std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { 212 return Sizes[N]; 213 } 214 /// Returns the base declaration of the reduction item. 215 const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } 216 /// Returns the base declaration of the reduction item. 217 const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; } 218 /// Returns true if the initialization of the reduction item uses initializer 219 /// from declare reduction construct. 220 bool usesReductionInitializer(unsigned N) const; 221 }; 222 223 class CGOpenMPRuntime { 224 public: 225 /// Allows to disable automatic handling of functions used in target regions 226 /// as those marked as `omp declare target`. 227 class DisableAutoDeclareTargetRAII { 228 CodeGenModule &CGM; 229 bool SavedShouldMarkAsGlobal; 230 231 public: 232 DisableAutoDeclareTargetRAII(CodeGenModule &CGM); 233 ~DisableAutoDeclareTargetRAII(); 234 }; 235 236 /// Manages list of nontemporal decls for the specified directive. 237 class NontemporalDeclsRAII { 238 CodeGenModule &CGM; 239 const bool NeedToPush; 240 241 public: 242 NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S); 243 ~NontemporalDeclsRAII(); 244 }; 245 246 /// Maps the expression for the lastprivate variable to the global copy used 247 /// to store new value because original variables are not mapped in inner 248 /// parallel regions. Only private copies are captured but we need also to 249 /// store private copy in shared address. 250 /// Also, stores the expression for the private loop counter and it 251 /// threaprivate name. 252 struct LastprivateConditionalData { 253 llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>> 254 DeclToUniqueName; 255 LValue IVLVal; 256 llvm::Function *Fn = nullptr; 257 bool Disabled = false; 258 }; 259 /// Manages list of lastprivate conditional decls for the specified directive. 260 class LastprivateConditionalRAII { 261 enum class ActionToDo { 262 DoNotPush, 263 PushAsLastprivateConditional, 264 DisableLastprivateConditional, 265 }; 266 CodeGenModule &CGM; 267 ActionToDo Action = ActionToDo::DoNotPush; 268 269 /// Check and try to disable analysis of inner regions for changes in 270 /// lastprivate conditional. 271 void tryToDisableInnerAnalysis(const OMPExecutableDirective &S, 272 llvm::DenseSet<CanonicalDeclPtr<const Decl>> 273 &NeedToAddForLPCsAsDisabled) const; 274 275 LastprivateConditionalRAII(CodeGenFunction &CGF, 276 const OMPExecutableDirective &S); 277 278 public: 279 explicit LastprivateConditionalRAII(CodeGenFunction &CGF, 280 const OMPExecutableDirective &S, 281 LValue IVLVal); 282 static LastprivateConditionalRAII disable(CodeGenFunction &CGF, 283 const OMPExecutableDirective &S); 284 ~LastprivateConditionalRAII(); 285 }; 286 287 protected: 288 CodeGenModule &CGM; 289 StringRef FirstSeparator, Separator; 290 291 /// Constructor allowing to redefine the name separator for the variables. 292 explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, 293 StringRef Separator); 294 295 /// Creates offloading entry for the provided entry ID \a ID, 296 /// address \a Addr, size \a Size, and flags \a Flags. 297 virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, 298 uint64_t Size, int32_t Flags, 299 llvm::GlobalValue::LinkageTypes Linkage); 300 301 /// Helper to emit outlined function for 'target' directive. 302 /// \param D Directive to emit. 303 /// \param ParentName Name of the function that encloses the target region. 304 /// \param OutlinedFn Outlined function value to be defined by this call. 305 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 306 /// \param IsOffloadEntry True if the outlined function is an offload entry. 307 /// \param CodeGen Lambda codegen specific to an accelerator device. 308 /// An outlined function may not be an entry if, e.g. the if clause always 309 /// evaluates to false. 310 virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, 311 StringRef ParentName, 312 llvm::Function *&OutlinedFn, 313 llvm::Constant *&OutlinedFnID, 314 bool IsOffloadEntry, 315 const RegionCodeGenTy &CodeGen); 316 317 /// Emits object of ident_t type with info for source location. 318 /// \param Flags Flags for OpenMP location. 319 /// 320 llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, 321 unsigned Flags = 0); 322 323 /// Returns pointer to ident_t type. 324 llvm::Type *getIdentTyPointerTy(); 325 326 /// Gets thread id value for the current thread. 327 /// 328 llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); 329 330 /// Get the function name of an outlined region. 331 // The name can be customized depending on the target. 332 // 333 virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } 334 335 /// Emits \p Callee function call with arguments \p Args with location \p Loc. 336 void emitCall(CodeGenFunction &CGF, SourceLocation Loc, 337 llvm::FunctionCallee Callee, 338 ArrayRef<llvm::Value *> Args = llvm::None) const; 339 340 /// Emits address of the word in a memory where current thread id is 341 /// stored. 342 virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); 343 344 void setLocThreadIdInsertPt(CodeGenFunction &CGF, 345 bool AtCurrentPoint = false); 346 void clearLocThreadIdInsertPt(CodeGenFunction &CGF); 347 348 /// Check if the default location must be constant. 349 /// Default is false to support OMPT/OMPD. 350 virtual bool isDefaultLocationConstant() const { return false; } 351 352 /// Returns additional flags that can be stored in reserved_2 field of the 353 /// default location. 354 virtual unsigned getDefaultLocationReserved2Flags() const { return 0; } 355 356 /// Returns default flags for the barriers depending on the directive, for 357 /// which this barier is going to be emitted. 358 static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind); 359 360 /// Get the LLVM type for the critical name. 361 llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;} 362 363 /// Returns corresponding lock object for the specified critical region 364 /// name. If the lock object does not exist it is created, otherwise the 365 /// reference to the existing copy is returned. 366 /// \param CriticalName Name of the critical region. 367 /// 368 llvm::Value *getCriticalRegionLock(StringRef CriticalName); 369 370 private: 371 /// Default const ident_t object used for initialization of all other 372 /// ident_t objects. 373 llvm::Constant *DefaultOpenMPPSource = nullptr; 374 using FlagsTy = std::pair<unsigned, unsigned>; 375 /// Map of flags and corresponding default locations. 376 using OpenMPDefaultLocMapTy = llvm::DenseMap<FlagsTy, llvm::Value *>; 377 OpenMPDefaultLocMapTy OpenMPDefaultLocMap; 378 Address getOrCreateDefaultLocation(unsigned Flags); 379 380 QualType IdentQTy; 381 llvm::StructType *IdentTy = nullptr; 382 /// Map for SourceLocation and OpenMP runtime library debug locations. 383 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy; 384 OpenMPDebugLocMapTy OpenMPDebugLocMap; 385 /// The type for a microtask which gets passed to __kmpc_fork_call(). 386 /// Original representation is: 387 /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); 388 llvm::FunctionType *Kmpc_MicroTy = nullptr; 389 /// Stores debug location and ThreadID for the function. 390 struct DebugLocThreadIdTy { 391 llvm::Value *DebugLoc; 392 llvm::Value *ThreadID; 393 /// Insert point for the service instructions. 394 llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr; 395 }; 396 /// Map of local debug location, ThreadId and functions. 397 typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> 398 OpenMPLocThreadIDMapTy; 399 OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; 400 /// Map of UDRs and corresponding combiner/initializer. 401 typedef llvm::DenseMap<const OMPDeclareReductionDecl *, 402 std::pair<llvm::Function *, llvm::Function *>> 403 UDRMapTy; 404 UDRMapTy UDRMap; 405 /// Map of functions and locally defined UDRs. 406 typedef llvm::DenseMap<llvm::Function *, 407 SmallVector<const OMPDeclareReductionDecl *, 4>> 408 FunctionUDRMapTy; 409 FunctionUDRMapTy FunctionUDRMap; 410 /// Map from the user-defined mapper declaration to its corresponding 411 /// functions. 412 llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap; 413 /// Map of functions and their local user-defined mappers. 414 using FunctionUDMMapTy = 415 llvm::DenseMap<llvm::Function *, 416 SmallVector<const OMPDeclareMapperDecl *, 4>>; 417 FunctionUDMMapTy FunctionUDMMap; 418 /// Maps local variables marked as lastprivate conditional to their internal 419 /// types. 420 llvm::DenseMap<llvm::Function *, 421 llvm::DenseMap<CanonicalDeclPtr<const Decl>, 422 std::tuple<QualType, const FieldDecl *, 423 const FieldDecl *, LValue>>> 424 LastprivateConditionalToTypes; 425 /// Type kmp_critical_name, originally defined as typedef kmp_int32 426 /// kmp_critical_name[8]; 427 llvm::ArrayType *KmpCriticalNameTy; 428 /// An ordered map of auto-generated variables to their unique names. 429 /// It stores variables with the following names: 1) ".gomp_critical_user_" + 430 /// <critical_section_name> + ".var" for "omp critical" directives; 2) 431 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate 432 /// variables. 433 llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator> 434 InternalVars; 435 /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); 436 llvm::Type *KmpRoutineEntryPtrTy = nullptr; 437 QualType KmpRoutineEntryPtrQTy; 438 /// Type typedef struct kmp_task { 439 /// void * shareds; /**< pointer to block of pointers to 440 /// shared vars */ 441 /// kmp_routine_entry_t routine; /**< pointer to routine to call for 442 /// executing task */ 443 /// kmp_int32 part_id; /**< part id for the task */ 444 /// kmp_routine_entry_t destructors; /* pointer to function to invoke 445 /// deconstructors of firstprivate C++ objects */ 446 /// } kmp_task_t; 447 QualType KmpTaskTQTy; 448 /// Saved kmp_task_t for task directive. 449 QualType SavedKmpTaskTQTy; 450 /// Saved kmp_task_t for taskloop-based directive. 451 QualType SavedKmpTaskloopTQTy; 452 /// Type typedef struct kmp_depend_info { 453 /// kmp_intptr_t base_addr; 454 /// size_t len; 455 /// struct { 456 /// bool in:1; 457 /// bool out:1; 458 /// } flags; 459 /// } kmp_depend_info_t; 460 QualType KmpDependInfoTy; 461 /// struct kmp_dim { // loop bounds info casted to kmp_int64 462 /// kmp_int64 lo; // lower 463 /// kmp_int64 up; // upper 464 /// kmp_int64 st; // stride 465 /// }; 466 QualType KmpDimTy; 467 /// Type struct __tgt_offload_entry{ 468 /// void *addr; // Pointer to the offload entry info. 469 /// // (function or global) 470 /// char *name; // Name of the function or global. 471 /// size_t size; // Size of the entry info (0 if it a function). 472 /// int32_t flags; 473 /// int32_t reserved; 474 /// }; 475 QualType TgtOffloadEntryQTy; 476 /// Entity that registers the offloading constants that were emitted so 477 /// far. 478 class OffloadEntriesInfoManagerTy { 479 CodeGenModule &CGM; 480 481 /// Number of entries registered so far. 482 unsigned OffloadingEntriesNum = 0; 483 484 public: 485 /// Base class of the entries info. 486 class OffloadEntryInfo { 487 public: 488 /// Kind of a given entry. 489 enum OffloadingEntryInfoKinds : unsigned { 490 /// Entry is a target region. 491 OffloadingEntryInfoTargetRegion = 0, 492 /// Entry is a declare target variable. 493 OffloadingEntryInfoDeviceGlobalVar = 1, 494 /// Invalid entry info. 495 OffloadingEntryInfoInvalid = ~0u 496 }; 497 498 protected: 499 OffloadEntryInfo() = delete; 500 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {} 501 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, 502 uint32_t Flags) 503 : Flags(Flags), Order(Order), Kind(Kind) {} 504 ~OffloadEntryInfo() = default; 505 506 public: 507 bool isValid() const { return Order != ~0u; } 508 unsigned getOrder() const { return Order; } 509 OffloadingEntryInfoKinds getKind() const { return Kind; } 510 uint32_t getFlags() const { return Flags; } 511 void setFlags(uint32_t NewFlags) { Flags = NewFlags; } 512 llvm::Constant *getAddress() const { 513 return cast_or_null<llvm::Constant>(Addr); 514 } 515 void setAddress(llvm::Constant *V) { 516 assert(!Addr.pointsToAliveValue() && "Address has been set before!"); 517 Addr = V; 518 } 519 static bool classof(const OffloadEntryInfo *Info) { return true; } 520 521 private: 522 /// Address of the entity that has to be mapped for offloading. 523 llvm::WeakTrackingVH Addr; 524 525 /// Flags associated with the device global. 526 uint32_t Flags = 0u; 527 528 /// Order this entry was emitted. 529 unsigned Order = ~0u; 530 531 OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid; 532 }; 533 534 /// Return true if a there are no entries defined. 535 bool empty() const; 536 /// Return number of entries defined so far. 537 unsigned size() const { return OffloadingEntriesNum; } 538 OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {} 539 540 // 541 // Target region entries related. 542 // 543 544 /// Kind of the target registry entry. 545 enum OMPTargetRegionEntryKind : uint32_t { 546 /// Mark the entry as target region. 547 OMPTargetRegionEntryTargetRegion = 0x0, 548 /// Mark the entry as a global constructor. 549 OMPTargetRegionEntryCtor = 0x02, 550 /// Mark the entry as a global destructor. 551 OMPTargetRegionEntryDtor = 0x04, 552 }; 553 554 /// Target region entries info. 555 class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo { 556 /// Address that can be used as the ID of the entry. 557 llvm::Constant *ID = nullptr; 558 559 public: 560 OffloadEntryInfoTargetRegion() 561 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {} 562 explicit OffloadEntryInfoTargetRegion(unsigned Order, 563 llvm::Constant *Addr, 564 llvm::Constant *ID, 565 OMPTargetRegionEntryKind Flags) 566 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags), 567 ID(ID) { 568 setAddress(Addr); 569 } 570 571 llvm::Constant *getID() const { return ID; } 572 void setID(llvm::Constant *V) { 573 assert(!ID && "ID has been set before!"); 574 ID = V; 575 } 576 static bool classof(const OffloadEntryInfo *Info) { 577 return Info->getKind() == OffloadingEntryInfoTargetRegion; 578 } 579 }; 580 581 /// Initialize target region entry. 582 void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 583 StringRef ParentName, unsigned LineNum, 584 unsigned Order); 585 /// Register target region entry. 586 void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 587 StringRef ParentName, unsigned LineNum, 588 llvm::Constant *Addr, llvm::Constant *ID, 589 OMPTargetRegionEntryKind Flags); 590 /// Return true if a target region entry with the provided information 591 /// exists. 592 bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 593 StringRef ParentName, unsigned LineNum) const; 594 /// brief Applies action \a Action on all registered entries. 595 typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, 596 const OffloadEntryInfoTargetRegion &)> 597 OffloadTargetRegionEntryInfoActTy; 598 void actOnTargetRegionEntriesInfo( 599 const OffloadTargetRegionEntryInfoActTy &Action); 600 601 // 602 // Device global variable entries related. 603 // 604 605 /// Kind of the global variable entry.. 606 enum OMPTargetGlobalVarEntryKind : uint32_t { 607 /// Mark the entry as a to declare target. 608 OMPTargetGlobalVarEntryTo = 0x0, 609 /// Mark the entry as a to declare target link. 610 OMPTargetGlobalVarEntryLink = 0x1, 611 }; 612 613 /// Device global variable entries info. 614 class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo { 615 /// Type of the global variable. 616 CharUnits VarSize; 617 llvm::GlobalValue::LinkageTypes Linkage; 618 619 public: 620 OffloadEntryInfoDeviceGlobalVar() 621 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {} 622 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, 623 OMPTargetGlobalVarEntryKind Flags) 624 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {} 625 explicit OffloadEntryInfoDeviceGlobalVar( 626 unsigned Order, llvm::Constant *Addr, CharUnits VarSize, 627 OMPTargetGlobalVarEntryKind Flags, 628 llvm::GlobalValue::LinkageTypes Linkage) 629 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags), 630 VarSize(VarSize), Linkage(Linkage) { 631 setAddress(Addr); 632 } 633 634 CharUnits getVarSize() const { return VarSize; } 635 void setVarSize(CharUnits Size) { VarSize = Size; } 636 llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } 637 void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; } 638 static bool classof(const OffloadEntryInfo *Info) { 639 return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar; 640 } 641 }; 642 643 /// Initialize device global variable entry. 644 void initializeDeviceGlobalVarEntryInfo(StringRef Name, 645 OMPTargetGlobalVarEntryKind Flags, 646 unsigned Order); 647 648 /// Register device global variable entry. 649 void 650 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, 651 CharUnits VarSize, 652 OMPTargetGlobalVarEntryKind Flags, 653 llvm::GlobalValue::LinkageTypes Linkage); 654 /// Checks if the variable with the given name has been registered already. 655 bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const { 656 return OffloadEntriesDeviceGlobalVar.count(VarName) > 0; 657 } 658 /// Applies action \a Action on all registered entries. 659 typedef llvm::function_ref<void(StringRef, 660 const OffloadEntryInfoDeviceGlobalVar &)> 661 OffloadDeviceGlobalVarEntryInfoActTy; 662 void actOnDeviceGlobalVarEntriesInfo( 663 const OffloadDeviceGlobalVarEntryInfoActTy &Action); 664 665 private: 666 // Storage for target region entries kind. The storage is to be indexed by 667 // file ID, device ID, parent function name and line number. 668 typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> 669 OffloadEntriesTargetRegionPerLine; 670 typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> 671 OffloadEntriesTargetRegionPerParentName; 672 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> 673 OffloadEntriesTargetRegionPerFile; 674 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> 675 OffloadEntriesTargetRegionPerDevice; 676 typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; 677 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; 678 /// Storage for device global variable entries kind. The storage is to be 679 /// indexed by mangled name. 680 typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar> 681 OffloadEntriesDeviceGlobalVarTy; 682 OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar; 683 }; 684 OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; 685 686 bool ShouldMarkAsGlobal = true; 687 /// List of the emitted declarations. 688 llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls; 689 /// List of the global variables with their addresses that should not be 690 /// emitted for the target. 691 llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables; 692 693 /// List of variables that can become declare target implicitly and, thus, 694 /// must be emitted. 695 llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables; 696 697 using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>; 698 /// Stack for list of declarations in current context marked as nontemporal. 699 /// The set is the union of all current stack elements. 700 llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack; 701 702 /// Stack for list of addresses of declarations in current context marked as 703 /// lastprivate conditional. The set is the union of all current stack 704 /// elements. 705 llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack; 706 707 /// Flag for keeping track of weather a requires unified_shared_memory 708 /// directive is present. 709 bool HasRequiresUnifiedSharedMemory = false; 710 711 /// Atomic ordering from the omp requires directive. 712 llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic; 713 714 /// Flag for keeping track of weather a target region has been emitted. 715 bool HasEmittedTargetRegion = false; 716 717 /// Flag for keeping track of weather a device routine has been emitted. 718 /// Device routines are specific to the 719 bool HasEmittedDeclareTargetRegion = false; 720 721 /// Loads all the offload entries information from the host IR 722 /// metadata. 723 void loadOffloadInfoMetadata(); 724 725 /// Returns __tgt_offload_entry type. 726 QualType getTgtOffloadEntryQTy(); 727 728 /// Start scanning from statement \a S and and emit all target regions 729 /// found along the way. 730 /// \param S Starting statement. 731 /// \param ParentName Name of the function declaration that is being scanned. 732 void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); 733 734 /// Build type kmp_routine_entry_t (if not built yet). 735 void emitKmpRoutineEntryT(QualType KmpInt32Ty); 736 737 /// Returns pointer to kmpc_micro type. 738 llvm::Type *getKmpc_MicroPointerTy(); 739 740 /// Returns specified OpenMP runtime function. 741 /// \param Function OpenMP runtime function. 742 /// \return Specified function. 743 llvm::FunctionCallee createRuntimeFunction(unsigned Function); 744 745 /// Returns __kmpc_for_static_init_* runtime function for the specified 746 /// size \a IVSize and sign \a IVSigned. 747 llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize, 748 bool IVSigned); 749 750 /// Returns __kmpc_dispatch_init_* runtime function for the specified 751 /// size \a IVSize and sign \a IVSigned. 752 llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize, 753 bool IVSigned); 754 755 /// Returns __kmpc_dispatch_next_* runtime function for the specified 756 /// size \a IVSize and sign \a IVSigned. 757 llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize, 758 bool IVSigned); 759 760 /// Returns __kmpc_dispatch_fini_* runtime function for the specified 761 /// size \a IVSize and sign \a IVSigned. 762 llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize, 763 bool IVSigned); 764 765 /// If the specified mangled name is not in the module, create and 766 /// return threadprivate cache object. This object is a pointer's worth of 767 /// storage that's reserved for use by the OpenMP runtime. 768 /// \param VD Threadprivate variable. 769 /// \return Cache variable for the specified threadprivate. 770 llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); 771 772 /// Gets (if variable with the given name already exist) or creates 773 /// internal global variable with the specified Name. The created variable has 774 /// linkage CommonLinkage by default and is initialized by null value. 775 /// \param Ty Type of the global variable. If it is exist already the type 776 /// must be the same. 777 /// \param Name Name of the variable. 778 llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty, 779 const llvm::Twine &Name, 780 unsigned AddressSpace = 0); 781 782 /// Set of threadprivate variables with the generated initializer. 783 llvm::StringSet<> ThreadPrivateWithDefinition; 784 785 /// Set of declare target variables with the generated initializer. 786 llvm::StringSet<> DeclareTargetWithDefinition; 787 788 /// Emits initialization code for the threadprivate variables. 789 /// \param VDAddr Address of the global variable \a VD. 790 /// \param Ctor Pointer to a global init function for \a VD. 791 /// \param CopyCtor Pointer to a global copy function for \a VD. 792 /// \param Dtor Pointer to a global destructor function for \a VD. 793 /// \param Loc Location of threadprivate declaration. 794 void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, 795 llvm::Value *Ctor, llvm::Value *CopyCtor, 796 llvm::Value *Dtor, SourceLocation Loc); 797 798 /// Emit the array initialization or deletion portion for user-defined mapper 799 /// code generation. 800 void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF, 801 llvm::Value *Handle, llvm::Value *BasePtr, 802 llvm::Value *Ptr, llvm::Value *Size, 803 llvm::Value *MapType, CharUnits ElementSize, 804 llvm::BasicBlock *ExitBB, bool IsInit); 805 806 struct TaskResultTy { 807 llvm::Value *NewTask = nullptr; 808 llvm::Function *TaskEntry = nullptr; 809 llvm::Value *NewTaskNewTaskTTy = nullptr; 810 LValue TDBase; 811 const RecordDecl *KmpTaskTQTyRD = nullptr; 812 llvm::Value *TaskDupFn = nullptr; 813 }; 814 /// Emit task region for the task directive. The task region is emitted in 815 /// several steps: 816 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 817 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 818 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 819 /// function: 820 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 821 /// TaskFunction(gtid, tt->part_id, tt->shareds); 822 /// return 0; 823 /// } 824 /// 2. Copy a list of shared variables to field shareds of the resulting 825 /// structure kmp_task_t returned by the previous call (if any). 826 /// 3. Copy a pointer to destructions function to field destructions of the 827 /// resulting structure kmp_task_t. 828 /// \param D Current task directive. 829 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 830 /// /*part_id*/, captured_struct */*__context*/); 831 /// \param SharedsTy A type which contains references the shared variables. 832 /// \param Shareds Context with the list of shared variables from the \p 833 /// TaskFunction. 834 /// \param Data Additional data for task generation like tiednsee, final 835 /// state, list of privates etc. 836 TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, 837 const OMPExecutableDirective &D, 838 llvm::Function *TaskFunction, QualType SharedsTy, 839 Address Shareds, const OMPTaskDataTy &Data); 840 841 /// Returns default address space for the constant firstprivates, 0 by 842 /// default. 843 virtual unsigned getDefaultFirstprivateAddressSpace() const { return 0; } 844 845 /// Emit code that pushes the trip count of loops associated with constructs 846 /// 'target teams distribute' and 'teams distribute parallel for'. 847 /// \param SizeEmitter Emits the int64 value for the number of iterations of 848 /// the associated loop. 849 void emitTargetNumIterationsCall( 850 CodeGenFunction &CGF, const OMPExecutableDirective &D, 851 llvm::Value *DeviceID, 852 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 853 const OMPLoopDirective &D)> 854 SizeEmitter); 855 856 /// Emit update for lastprivate conditional data. 857 void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal, 858 StringRef UniqueDeclName, LValue LVal, 859 SourceLocation Loc); 860 861 /// Returns the number of the elements and the address of the depobj 862 /// dependency array. 863 /// \return Number of elements in depobj array and the pointer to the array of 864 /// dependencies. 865 std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF, 866 LValue DepobjLVal, 867 SourceLocation Loc); 868 869 public: 870 explicit CGOpenMPRuntime(CodeGenModule &CGM) 871 : CGOpenMPRuntime(CGM, ".", ".") {} 872 virtual ~CGOpenMPRuntime() {} 873 virtual void clear(); 874 875 /// Emits code for OpenMP 'if' clause using specified \a CodeGen 876 /// function. Here is the logic: 877 /// if (Cond) { 878 /// ThenGen(); 879 /// } else { 880 /// ElseGen(); 881 /// } 882 void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, 883 const RegionCodeGenTy &ThenGen, 884 const RegionCodeGenTy &ElseGen); 885 886 /// Checks if the \p Body is the \a CompoundStmt and returns its child 887 /// statement iff there is only one that is not evaluatable at the compile 888 /// time. 889 static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body); 890 891 /// Get the platform-specific name separator. 892 std::string getName(ArrayRef<StringRef> Parts) const; 893 894 /// Emit code for the specified user defined reduction construct. 895 virtual void emitUserDefinedReduction(CodeGenFunction *CGF, 896 const OMPDeclareReductionDecl *D); 897 /// Get combiner/initializer for the specified user-defined reduction, if any. 898 virtual std::pair<llvm::Function *, llvm::Function *> 899 getUserDefinedReduction(const OMPDeclareReductionDecl *D); 900 901 /// Emit the function for the user defined mapper construct. 902 void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, 903 CodeGenFunction *CGF = nullptr); 904 905 /// Emits outlined function for the specified OpenMP parallel directive 906 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 907 /// kmp_int32 BoundID, struct context_vars*). 908 /// \param D OpenMP directive. 909 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 910 /// \param InnermostKind Kind of innermost directive (for simple directives it 911 /// is a directive itself, for combined - its innermost directive). 912 /// \param CodeGen Code generation sequence for the \a D directive. 913 virtual llvm::Function *emitParallelOutlinedFunction( 914 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 915 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 916 917 /// Emits outlined function for the specified OpenMP teams directive 918 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 919 /// kmp_int32 BoundID, struct context_vars*). 920 /// \param D OpenMP directive. 921 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 922 /// \param InnermostKind Kind of innermost directive (for simple directives it 923 /// is a directive itself, for combined - its innermost directive). 924 /// \param CodeGen Code generation sequence for the \a D directive. 925 virtual llvm::Function *emitTeamsOutlinedFunction( 926 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 927 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 928 929 /// Emits outlined function for the OpenMP task directive \a D. This 930 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 931 /// TaskT). 932 /// \param D OpenMP directive. 933 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 934 /// \param PartIDVar Variable for partition id in the current OpenMP untied 935 /// task region. 936 /// \param TaskTVar Variable for task_t argument. 937 /// \param InnermostKind Kind of innermost directive (for simple directives it 938 /// is a directive itself, for combined - its innermost directive). 939 /// \param CodeGen Code generation sequence for the \a D directive. 940 /// \param Tied true if task is generated for tied task, false otherwise. 941 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 942 /// tasks. 943 /// 944 virtual llvm::Function *emitTaskOutlinedFunction( 945 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 946 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 947 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 948 bool Tied, unsigned &NumberOfParts); 949 950 /// Cleans up references to the objects in finished function. 951 /// 952 virtual void functionFinished(CodeGenFunction &CGF); 953 954 /// Emits code for parallel or serial call of the \a OutlinedFn with 955 /// variables captured in a record which address is stored in \a 956 /// CapturedStruct. 957 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 958 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 959 /// \param CapturedVars A pointer to the record with the references to 960 /// variables used in \a OutlinedFn function. 961 /// \param IfCond Condition in the associated 'if' clause, if it was 962 /// specified, nullptr otherwise. 963 /// 964 virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 965 llvm::Function *OutlinedFn, 966 ArrayRef<llvm::Value *> CapturedVars, 967 const Expr *IfCond); 968 969 /// Emits a critical region. 970 /// \param CriticalName Name of the critical region. 971 /// \param CriticalOpGen Generator for the statement associated with the given 972 /// critical region. 973 /// \param Hint Value of the 'hint' clause (optional). 974 virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 975 const RegionCodeGenTy &CriticalOpGen, 976 SourceLocation Loc, 977 const Expr *Hint = nullptr); 978 979 /// Emits a master region. 980 /// \param MasterOpGen Generator for the statement associated with the given 981 /// master region. 982 virtual void emitMasterRegion(CodeGenFunction &CGF, 983 const RegionCodeGenTy &MasterOpGen, 984 SourceLocation Loc); 985 986 /// Emits code for a taskyield directive. 987 virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); 988 989 /// Emit a taskgroup region. 990 /// \param TaskgroupOpGen Generator for the statement associated with the 991 /// given taskgroup region. 992 virtual void emitTaskgroupRegion(CodeGenFunction &CGF, 993 const RegionCodeGenTy &TaskgroupOpGen, 994 SourceLocation Loc); 995 996 /// Emits a single region. 997 /// \param SingleOpGen Generator for the statement associated with the given 998 /// single region. 999 virtual void emitSingleRegion(CodeGenFunction &CGF, 1000 const RegionCodeGenTy &SingleOpGen, 1001 SourceLocation Loc, 1002 ArrayRef<const Expr *> CopyprivateVars, 1003 ArrayRef<const Expr *> DestExprs, 1004 ArrayRef<const Expr *> SrcExprs, 1005 ArrayRef<const Expr *> AssignmentOps); 1006 1007 /// Emit an ordered region. 1008 /// \param OrderedOpGen Generator for the statement associated with the given 1009 /// ordered region. 1010 virtual void emitOrderedRegion(CodeGenFunction &CGF, 1011 const RegionCodeGenTy &OrderedOpGen, 1012 SourceLocation Loc, bool IsThreads); 1013 1014 /// Emit an implicit/explicit barrier for OpenMP threads. 1015 /// \param Kind Directive for which this implicit barrier call must be 1016 /// generated. Must be OMPD_barrier for explicit barrier generation. 1017 /// \param EmitChecks true if need to emit checks for cancellation barriers. 1018 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 1019 /// runtime class decides which one to emit (simple or with cancellation 1020 /// checks). 1021 /// 1022 virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 1023 OpenMPDirectiveKind Kind, 1024 bool EmitChecks = true, 1025 bool ForceSimpleCall = false); 1026 1027 /// Check if the specified \a ScheduleKind is static non-chunked. 1028 /// This kind of worksharing directive is emitted without outer loop. 1029 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. 1030 /// \param Chunked True if chunk is specified in the clause. 1031 /// 1032 virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, 1033 bool Chunked) const; 1034 1035 /// Check if the specified \a ScheduleKind is static non-chunked. 1036 /// This kind of distribute directive is emitted without outer loop. 1037 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. 1038 /// \param Chunked True if chunk is specified in the clause. 1039 /// 1040 virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, 1041 bool Chunked) const; 1042 1043 /// Check if the specified \a ScheduleKind is static chunked. 1044 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. 1045 /// \param Chunked True if chunk is specified in the clause. 1046 /// 1047 virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, 1048 bool Chunked) const; 1049 1050 /// Check if the specified \a ScheduleKind is static non-chunked. 1051 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. 1052 /// \param Chunked True if chunk is specified in the clause. 1053 /// 1054 virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind, 1055 bool Chunked) const; 1056 1057 /// Check if the specified \a ScheduleKind is dynamic. 1058 /// This kind of worksharing directive is emitted without outer loop. 1059 /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. 1060 /// 1061 virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; 1062 1063 /// struct with the values to be passed to the dispatch runtime function 1064 struct DispatchRTInput { 1065 /// Loop lower bound 1066 llvm::Value *LB = nullptr; 1067 /// Loop upper bound 1068 llvm::Value *UB = nullptr; 1069 /// Chunk size specified using 'schedule' clause (nullptr if chunk 1070 /// was not specified) 1071 llvm::Value *Chunk = nullptr; 1072 DispatchRTInput() = default; 1073 DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) 1074 : LB(LB), UB(UB), Chunk(Chunk) {} 1075 }; 1076 1077 /// Call the appropriate runtime routine to initialize it before start 1078 /// of loop. 1079 1080 /// This is used for non static scheduled types and when the ordered 1081 /// clause is present on the loop construct. 1082 /// Depending on the loop schedule, it is necessary to call some runtime 1083 /// routine before start of the OpenMP loop to get the loop upper / lower 1084 /// bounds \a LB and \a UB and stride \a ST. 1085 /// 1086 /// \param CGF Reference to current CodeGenFunction. 1087 /// \param Loc Clang source location. 1088 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1089 /// \param IVSize Size of the iteration variable in bits. 1090 /// \param IVSigned Sign of the iteration variable. 1091 /// \param Ordered true if loop is ordered, false otherwise. 1092 /// \param DispatchValues struct containing llvm values for lower bound, upper 1093 /// bound, and chunk expression. 1094 /// For the default (nullptr) value, the chunk 1 will be used. 1095 /// 1096 virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 1097 const OpenMPScheduleTy &ScheduleKind, 1098 unsigned IVSize, bool IVSigned, bool Ordered, 1099 const DispatchRTInput &DispatchValues); 1100 1101 /// Struct with the values to be passed to the static runtime function 1102 struct StaticRTInput { 1103 /// Size of the iteration variable in bits. 1104 unsigned IVSize = 0; 1105 /// Sign of the iteration variable. 1106 bool IVSigned = false; 1107 /// true if loop is ordered, false otherwise. 1108 bool Ordered = false; 1109 /// Address of the output variable in which the flag of the last iteration 1110 /// is returned. 1111 Address IL = Address::invalid(); 1112 /// Address of the output variable in which the lower iteration number is 1113 /// returned. 1114 Address LB = Address::invalid(); 1115 /// Address of the output variable in which the upper iteration number is 1116 /// returned. 1117 Address UB = Address::invalid(); 1118 /// Address of the output variable in which the stride value is returned 1119 /// necessary to generated the static_chunked scheduled loop. 1120 Address ST = Address::invalid(); 1121 /// Value of the chunk for the static_chunked scheduled loop. For the 1122 /// default (nullptr) value, the chunk 1 will be used. 1123 llvm::Value *Chunk = nullptr; 1124 StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, 1125 Address LB, Address UB, Address ST, 1126 llvm::Value *Chunk = nullptr) 1127 : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), 1128 UB(UB), ST(ST), Chunk(Chunk) {} 1129 }; 1130 /// Call the appropriate runtime routine to initialize it before start 1131 /// of loop. 1132 /// 1133 /// This is used only in case of static schedule, when the user did not 1134 /// specify a ordered clause on the loop construct. 1135 /// Depending on the loop schedule, it is necessary to call some runtime 1136 /// routine before start of the OpenMP loop to get the loop upper / lower 1137 /// bounds LB and UB and stride ST. 1138 /// 1139 /// \param CGF Reference to current CodeGenFunction. 1140 /// \param Loc Clang source location. 1141 /// \param DKind Kind of the directive. 1142 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1143 /// \param Values Input arguments for the construct. 1144 /// 1145 virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1146 OpenMPDirectiveKind DKind, 1147 const OpenMPScheduleTy &ScheduleKind, 1148 const StaticRTInput &Values); 1149 1150 /// 1151 /// \param CGF Reference to current CodeGenFunction. 1152 /// \param Loc Clang source location. 1153 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 1154 /// \param Values Input arguments for the construct. 1155 /// 1156 virtual void emitDistributeStaticInit(CodeGenFunction &CGF, 1157 SourceLocation Loc, 1158 OpenMPDistScheduleClauseKind SchedKind, 1159 const StaticRTInput &Values); 1160 1161 /// Call the appropriate runtime routine to notify that we finished 1162 /// iteration of the ordered loop with the dynamic scheduling. 1163 /// 1164 /// \param CGF Reference to current CodeGenFunction. 1165 /// \param Loc Clang source location. 1166 /// \param IVSize Size of the iteration variable in bits. 1167 /// \param IVSigned Sign of the iteration variable. 1168 /// 1169 virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, 1170 SourceLocation Loc, unsigned IVSize, 1171 bool IVSigned); 1172 1173 /// Call the appropriate runtime routine to notify that we finished 1174 /// all the work with current loop. 1175 /// 1176 /// \param CGF Reference to current CodeGenFunction. 1177 /// \param Loc Clang source location. 1178 /// \param DKind Kind of the directive for which the static finish is emitted. 1179 /// 1180 virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 1181 OpenMPDirectiveKind DKind); 1182 1183 /// Call __kmpc_dispatch_next( 1184 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 1185 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 1186 /// kmp_int[32|64] *p_stride); 1187 /// \param IVSize Size of the iteration variable in bits. 1188 /// \param IVSigned Sign of the iteration variable. 1189 /// \param IL Address of the output variable in which the flag of the 1190 /// last iteration is returned. 1191 /// \param LB Address of the output variable in which the lower iteration 1192 /// number is returned. 1193 /// \param UB Address of the output variable in which the upper iteration 1194 /// number is returned. 1195 /// \param ST Address of the output variable in which the stride value is 1196 /// returned. 1197 virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 1198 unsigned IVSize, bool IVSigned, 1199 Address IL, Address LB, 1200 Address UB, Address ST); 1201 1202 /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 1203 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 1204 /// clause. 1205 /// \param NumThreads An integer value of threads. 1206 virtual void emitNumThreadsClause(CodeGenFunction &CGF, 1207 llvm::Value *NumThreads, 1208 SourceLocation Loc); 1209 1210 /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 1211 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 1212 virtual void emitProcBindClause(CodeGenFunction &CGF, 1213 llvm::omp::ProcBindKind ProcBind, 1214 SourceLocation Loc); 1215 1216 /// Returns address of the threadprivate variable for the current 1217 /// thread. 1218 /// \param VD Threadprivate variable. 1219 /// \param VDAddr Address of the global variable \a VD. 1220 /// \param Loc Location of the reference to threadprivate var. 1221 /// \return Address of the threadprivate variable for the current thread. 1222 virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, 1223 const VarDecl *VD, 1224 Address VDAddr, 1225 SourceLocation Loc); 1226 1227 /// Returns the address of the variable marked as declare target with link 1228 /// clause OR as declare target with to clause and unified memory. 1229 virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD); 1230 1231 /// Emit a code for initialization of threadprivate variable. It emits 1232 /// a call to runtime library which adds initial value to the newly created 1233 /// threadprivate variable (if it is not constant) and registers destructor 1234 /// for the variable (if any). 1235 /// \param VD Threadprivate variable. 1236 /// \param VDAddr Address of the global variable \a VD. 1237 /// \param Loc Location of threadprivate declaration. 1238 /// \param PerformInit true if initialization expression is not constant. 1239 virtual llvm::Function * 1240 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 1241 SourceLocation Loc, bool PerformInit, 1242 CodeGenFunction *CGF = nullptr); 1243 1244 /// Emit a code for initialization of declare target variable. 1245 /// \param VD Declare target variable. 1246 /// \param Addr Address of the global variable \a VD. 1247 /// \param PerformInit true if initialization expression is not constant. 1248 virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD, 1249 llvm::GlobalVariable *Addr, 1250 bool PerformInit); 1251 1252 /// Creates artificial threadprivate variable with name \p Name and type \p 1253 /// VarType. 1254 /// \param VarType Type of the artificial threadprivate variable. 1255 /// \param Name Name of the artificial threadprivate variable. 1256 virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 1257 QualType VarType, 1258 StringRef Name); 1259 1260 /// Emit flush of the variables specified in 'omp flush' directive. 1261 /// \param Vars List of variables to flush. 1262 virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 1263 SourceLocation Loc, llvm::AtomicOrdering AO); 1264 1265 /// Emit task region for the task directive. The task region is 1266 /// emitted in several steps: 1267 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1268 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1269 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1270 /// function: 1271 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1272 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1273 /// return 0; 1274 /// } 1275 /// 2. Copy a list of shared variables to field shareds of the resulting 1276 /// structure kmp_task_t returned by the previous call (if any). 1277 /// 3. Copy a pointer to destructions function to field destructions of the 1278 /// resulting structure kmp_task_t. 1279 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 1280 /// kmp_task_t *new_task), where new_task is a resulting structure from 1281 /// previous items. 1282 /// \param D Current task directive. 1283 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1284 /// /*part_id*/, captured_struct */*__context*/); 1285 /// \param SharedsTy A type which contains references the shared variables. 1286 /// \param Shareds Context with the list of shared variables from the \p 1287 /// TaskFunction. 1288 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1289 /// otherwise. 1290 /// \param Data Additional data for task generation like tiednsee, final 1291 /// state, list of privates etc. 1292 virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 1293 const OMPExecutableDirective &D, 1294 llvm::Function *TaskFunction, QualType SharedsTy, 1295 Address Shareds, const Expr *IfCond, 1296 const OMPTaskDataTy &Data); 1297 1298 /// Emit task region for the taskloop directive. The taskloop region is 1299 /// emitted in several steps: 1300 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1301 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1302 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1303 /// function: 1304 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1305 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1306 /// return 0; 1307 /// } 1308 /// 2. Copy a list of shared variables to field shareds of the resulting 1309 /// structure kmp_task_t returned by the previous call (if any). 1310 /// 3. Copy a pointer to destructions function to field destructions of the 1311 /// resulting structure kmp_task_t. 1312 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 1313 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 1314 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 1315 /// is a resulting structure from 1316 /// previous items. 1317 /// \param D Current task directive. 1318 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1319 /// /*part_id*/, captured_struct */*__context*/); 1320 /// \param SharedsTy A type which contains references the shared variables. 1321 /// \param Shareds Context with the list of shared variables from the \p 1322 /// TaskFunction. 1323 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1324 /// otherwise. 1325 /// \param Data Additional data for task generation like tiednsee, final 1326 /// state, list of privates etc. 1327 virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 1328 const OMPLoopDirective &D, 1329 llvm::Function *TaskFunction, 1330 QualType SharedsTy, Address Shareds, 1331 const Expr *IfCond, const OMPTaskDataTy &Data); 1332 1333 /// Emit code for the directive that does not require outlining. 1334 /// 1335 /// \param InnermostKind Kind of innermost directive (for simple directives it 1336 /// is a directive itself, for combined - its innermost directive). 1337 /// \param CodeGen Code generation sequence for the \a D directive. 1338 /// \param HasCancel true if region has inner cancel directive, false 1339 /// otherwise. 1340 virtual void emitInlinedDirective(CodeGenFunction &CGF, 1341 OpenMPDirectiveKind InnermostKind, 1342 const RegionCodeGenTy &CodeGen, 1343 bool HasCancel = false); 1344 1345 /// Emits reduction function. 1346 /// \param ArgsType Array type containing pointers to reduction variables. 1347 /// \param Privates List of private copies for original reduction arguments. 1348 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1349 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1350 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1351 /// or 'operator binop(LHS, RHS)'. 1352 llvm::Function *emitReductionFunction(SourceLocation Loc, 1353 llvm::Type *ArgsType, 1354 ArrayRef<const Expr *> Privates, 1355 ArrayRef<const Expr *> LHSExprs, 1356 ArrayRef<const Expr *> RHSExprs, 1357 ArrayRef<const Expr *> ReductionOps); 1358 1359 /// Emits single reduction combiner 1360 void emitSingleReductionCombiner(CodeGenFunction &CGF, 1361 const Expr *ReductionOp, 1362 const Expr *PrivateRef, 1363 const DeclRefExpr *LHS, 1364 const DeclRefExpr *RHS); 1365 1366 struct ReductionOptionsTy { 1367 bool WithNowait; 1368 bool SimpleReduction; 1369 OpenMPDirectiveKind ReductionKind; 1370 }; 1371 /// Emit a code for reduction clause. Next code should be emitted for 1372 /// reduction: 1373 /// \code 1374 /// 1375 /// static kmp_critical_name lock = { 0 }; 1376 /// 1377 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 1378 /// ... 1379 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 1380 /// ... 1381 /// } 1382 /// 1383 /// ... 1384 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 1385 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 1386 /// RedList, reduce_func, &<lock>)) { 1387 /// case 1: 1388 /// ... 1389 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 1390 /// ... 1391 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 1392 /// break; 1393 /// case 2: 1394 /// ... 1395 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 1396 /// ... 1397 /// break; 1398 /// default:; 1399 /// } 1400 /// \endcode 1401 /// 1402 /// \param Privates List of private copies for original reduction arguments. 1403 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1404 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1405 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1406 /// or 'operator binop(LHS, RHS)'. 1407 /// \param Options List of options for reduction codegen: 1408 /// WithNowait true if parent directive has also nowait clause, false 1409 /// otherwise. 1410 /// SimpleReduction Emit reduction operation only. Used for omp simd 1411 /// directive on the host. 1412 /// ReductionKind The kind of reduction to perform. 1413 virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 1414 ArrayRef<const Expr *> Privates, 1415 ArrayRef<const Expr *> LHSExprs, 1416 ArrayRef<const Expr *> RHSExprs, 1417 ArrayRef<const Expr *> ReductionOps, 1418 ReductionOptionsTy Options); 1419 1420 /// Emit a code for initialization of task reduction clause. Next code 1421 /// should be emitted for reduction: 1422 /// \code 1423 /// 1424 /// _taskred_item_t red_data[n]; 1425 /// ... 1426 /// red_data[i].shar = &shareds[i]; 1427 /// red_data[i].orig = &origs[i]; 1428 /// red_data[i].size = sizeof(origs[i]); 1429 /// red_data[i].f_init = (void*)RedInit<i>; 1430 /// red_data[i].f_fini = (void*)RedDest<i>; 1431 /// red_data[i].f_comb = (void*)RedOp<i>; 1432 /// red_data[i].flags = <Flag_i>; 1433 /// ... 1434 /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); 1435 /// \endcode 1436 /// For reduction clause with task modifier it emits the next call: 1437 /// \code 1438 /// 1439 /// _taskred_item_t red_data[n]; 1440 /// ... 1441 /// red_data[i].shar = &shareds[i]; 1442 /// red_data[i].orig = &origs[i]; 1443 /// red_data[i].size = sizeof(origs[i]); 1444 /// red_data[i].f_init = (void*)RedInit<i>; 1445 /// red_data[i].f_fini = (void*)RedDest<i>; 1446 /// red_data[i].f_comb = (void*)RedOp<i>; 1447 /// red_data[i].flags = <Flag_i>; 1448 /// ... 1449 /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, 1450 /// red_data); 1451 /// \endcode 1452 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 1453 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 1454 /// \param Data Additional data for task generation like tiedness, final 1455 /// state, list of privates, reductions etc. 1456 virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, 1457 SourceLocation Loc, 1458 ArrayRef<const Expr *> LHSExprs, 1459 ArrayRef<const Expr *> RHSExprs, 1460 const OMPTaskDataTy &Data); 1461 1462 /// Emits the following code for reduction clause with task modifier: 1463 /// \code 1464 /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); 1465 /// \endcode 1466 virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, 1467 bool IsWorksharingReduction); 1468 1469 /// Required to resolve existing problems in the runtime. Emits threadprivate 1470 /// variables to store the size of the VLAs/array sections for 1471 /// initializer/combiner/finalizer functions. 1472 /// \param RCG Allows to reuse an existing data for the reductions. 1473 /// \param N Reduction item for which fixups must be emitted. 1474 virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 1475 ReductionCodeGen &RCG, unsigned N); 1476 1477 /// Get the address of `void *` type of the privatue copy of the reduction 1478 /// item specified by the \p SharedLVal. 1479 /// \param ReductionsPtr Pointer to the reduction data returned by the 1480 /// emitTaskReductionInit function. 1481 /// \param SharedLVal Address of the original reduction item. 1482 virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 1483 llvm::Value *ReductionsPtr, 1484 LValue SharedLVal); 1485 1486 /// Emit code for 'taskwait' directive. 1487 virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc); 1488 1489 /// Emit code for 'cancellation point' construct. 1490 /// \param CancelRegion Region kind for which the cancellation point must be 1491 /// emitted. 1492 /// 1493 virtual void emitCancellationPointCall(CodeGenFunction &CGF, 1494 SourceLocation Loc, 1495 OpenMPDirectiveKind CancelRegion); 1496 1497 /// Emit code for 'cancel' construct. 1498 /// \param IfCond Condition in the associated 'if' clause, if it was 1499 /// specified, nullptr otherwise. 1500 /// \param CancelRegion Region kind for which the cancel must be emitted. 1501 /// 1502 virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 1503 const Expr *IfCond, 1504 OpenMPDirectiveKind CancelRegion); 1505 1506 /// Emit outilined function for 'target' directive. 1507 /// \param D Directive to emit. 1508 /// \param ParentName Name of the function that encloses the target region. 1509 /// \param OutlinedFn Outlined function value to be defined by this call. 1510 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 1511 /// \param IsOffloadEntry True if the outlined function is an offload entry. 1512 /// \param CodeGen Code generation sequence for the \a D directive. 1513 /// An outlined function may not be an entry if, e.g. the if clause always 1514 /// evaluates to false. 1515 virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 1516 StringRef ParentName, 1517 llvm::Function *&OutlinedFn, 1518 llvm::Constant *&OutlinedFnID, 1519 bool IsOffloadEntry, 1520 const RegionCodeGenTy &CodeGen); 1521 1522 /// Emit the target offloading code associated with \a D. The emitted 1523 /// code attempts offloading the execution to the device, an the event of 1524 /// a failure it executes the host version outlined in \a OutlinedFn. 1525 /// \param D Directive to emit. 1526 /// \param OutlinedFn Host version of the code to be offloaded. 1527 /// \param OutlinedFnID ID of host version of the code to be offloaded. 1528 /// \param IfCond Expression evaluated in if clause associated with the target 1529 /// directive, or null if no if clause is used. 1530 /// \param Device Expression evaluated in device clause associated with the 1531 /// target directive, or null if no device clause is used and device modifier. 1532 /// \param SizeEmitter Callback to emit number of iterations for loop-based 1533 /// directives. 1534 virtual void emitTargetCall( 1535 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1536 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, 1537 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, 1538 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 1539 const OMPLoopDirective &D)> 1540 SizeEmitter); 1541 1542 /// Emit the target regions enclosed in \a GD function definition or 1543 /// the function itself in case it is a valid device function. Returns true if 1544 /// \a GD was dealt with successfully. 1545 /// \param GD Function to scan. 1546 virtual bool emitTargetFunctions(GlobalDecl GD); 1547 1548 /// Emit the global variable if it is a valid device global variable. 1549 /// Returns true if \a GD was dealt with successfully. 1550 /// \param GD Variable declaration to emit. 1551 virtual bool emitTargetGlobalVariable(GlobalDecl GD); 1552 1553 /// Checks if the provided global decl \a GD is a declare target variable and 1554 /// registers it when emitting code for the host. 1555 virtual void registerTargetGlobalVariable(const VarDecl *VD, 1556 llvm::Constant *Addr); 1557 1558 /// Registers provided target firstprivate variable as global on the 1559 /// target. 1560 llvm::Constant *registerTargetFirstprivateCopy(CodeGenFunction &CGF, 1561 const VarDecl *VD); 1562 1563 /// Emit the global \a GD if it is meaningful for the target. Returns 1564 /// if it was emitted successfully. 1565 /// \param GD Global to scan. 1566 virtual bool emitTargetGlobal(GlobalDecl GD); 1567 1568 /// Creates and returns a registration function for when at least one 1569 /// requires directives was used in the current module. 1570 llvm::Function *emitRequiresDirectiveRegFun(); 1571 1572 /// Creates all the offload entries in the current compilation unit 1573 /// along with the associated metadata. 1574 void createOffloadEntriesAndInfoMetadata(); 1575 1576 /// Emits code for teams call of the \a OutlinedFn with 1577 /// variables captured in a record which address is stored in \a 1578 /// CapturedStruct. 1579 /// \param OutlinedFn Outlined function to be run by team masters. Type of 1580 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1581 /// \param CapturedVars A pointer to the record with the references to 1582 /// variables used in \a OutlinedFn function. 1583 /// 1584 virtual void emitTeamsCall(CodeGenFunction &CGF, 1585 const OMPExecutableDirective &D, 1586 SourceLocation Loc, llvm::Function *OutlinedFn, 1587 ArrayRef<llvm::Value *> CapturedVars); 1588 1589 /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 1590 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 1591 /// for num_teams clause. 1592 /// \param NumTeams An integer expression of teams. 1593 /// \param ThreadLimit An integer expression of threads. 1594 virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 1595 const Expr *ThreadLimit, SourceLocation Loc); 1596 1597 /// Struct that keeps all the relevant information that should be kept 1598 /// throughout a 'target data' region. 1599 class TargetDataInfo { 1600 /// Set to true if device pointer information have to be obtained. 1601 bool RequiresDevicePointerInfo = false; 1602 1603 public: 1604 /// The array of base pointer passed to the runtime library. 1605 llvm::Value *BasePointersArray = nullptr; 1606 /// The array of section pointers passed to the runtime library. 1607 llvm::Value *PointersArray = nullptr; 1608 /// The array of sizes passed to the runtime library. 1609 llvm::Value *SizesArray = nullptr; 1610 /// The array of map types passed to the runtime library. 1611 llvm::Value *MapTypesArray = nullptr; 1612 /// The total number of pointers passed to the runtime library. 1613 unsigned NumberOfPtrs = 0u; 1614 /// Map between the a declaration of a capture and the corresponding base 1615 /// pointer address where the runtime returns the device pointers. 1616 llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; 1617 1618 explicit TargetDataInfo() {} 1619 explicit TargetDataInfo(bool RequiresDevicePointerInfo) 1620 : RequiresDevicePointerInfo(RequiresDevicePointerInfo) {} 1621 /// Clear information about the data arrays. 1622 void clearArrayInfo() { 1623 BasePointersArray = nullptr; 1624 PointersArray = nullptr; 1625 SizesArray = nullptr; 1626 MapTypesArray = nullptr; 1627 NumberOfPtrs = 0u; 1628 } 1629 /// Return true if the current target data information has valid arrays. 1630 bool isValid() { 1631 return BasePointersArray && PointersArray && SizesArray && 1632 MapTypesArray && NumberOfPtrs; 1633 } 1634 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } 1635 }; 1636 1637 /// Emit the target data mapping code associated with \a D. 1638 /// \param D Directive to emit. 1639 /// \param IfCond Expression evaluated in if clause associated with the 1640 /// target directive, or null if no device clause is used. 1641 /// \param Device Expression evaluated in device clause associated with the 1642 /// target directive, or null if no device clause is used. 1643 /// \param Info A record used to store information that needs to be preserved 1644 /// until the region is closed. 1645 virtual void emitTargetDataCalls(CodeGenFunction &CGF, 1646 const OMPExecutableDirective &D, 1647 const Expr *IfCond, const Expr *Device, 1648 const RegionCodeGenTy &CodeGen, 1649 TargetDataInfo &Info); 1650 1651 /// Emit the data mapping/movement code associated with the directive 1652 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 1653 /// \param D Directive to emit. 1654 /// \param IfCond Expression evaluated in if clause associated with the target 1655 /// directive, or null if no if clause is used. 1656 /// \param Device Expression evaluated in device clause associated with the 1657 /// target directive, or null if no device clause is used. 1658 virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 1659 const OMPExecutableDirective &D, 1660 const Expr *IfCond, 1661 const Expr *Device); 1662 1663 /// Marks function \a Fn with properly mangled versions of vector functions. 1664 /// \param FD Function marked as 'declare simd'. 1665 /// \param Fn LLVM function that must be marked with 'declare simd' 1666 /// attributes. 1667 virtual void emitDeclareSimdFunction(const FunctionDecl *FD, 1668 llvm::Function *Fn); 1669 1670 /// Emit initialization for doacross loop nesting support. 1671 /// \param D Loop-based construct used in doacross nesting construct. 1672 virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, 1673 ArrayRef<Expr *> NumIterations); 1674 1675 /// Emit code for doacross ordered directive with 'depend' clause. 1676 /// \param C 'depend' clause with 'sink|source' dependency kind. 1677 virtual void emitDoacrossOrdered(CodeGenFunction &CGF, 1678 const OMPDependClause *C); 1679 1680 /// Translates the native parameter of outlined function if this is required 1681 /// for target. 1682 /// \param FD Field decl from captured record for the parameter. 1683 /// \param NativeParam Parameter itself. 1684 virtual const VarDecl *translateParameter(const FieldDecl *FD, 1685 const VarDecl *NativeParam) const { 1686 return NativeParam; 1687 } 1688 1689 /// Gets the address of the native argument basing on the address of the 1690 /// target-specific parameter. 1691 /// \param NativeParam Parameter itself. 1692 /// \param TargetParam Corresponding target-specific parameter. 1693 virtual Address getParameterAddress(CodeGenFunction &CGF, 1694 const VarDecl *NativeParam, 1695 const VarDecl *TargetParam) const; 1696 1697 /// Choose default schedule type and chunk value for the 1698 /// dist_schedule clause. 1699 virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, 1700 const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, 1701 llvm::Value *&Chunk) const {} 1702 1703 /// Choose default schedule type and chunk value for the 1704 /// schedule clause. 1705 virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, 1706 const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, 1707 const Expr *&ChunkExpr) const; 1708 1709 /// Emits call of the outlined function with the provided arguments, 1710 /// translating these arguments to correct target-specific arguments. 1711 virtual void 1712 emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, 1713 llvm::FunctionCallee OutlinedFn, 1714 ArrayRef<llvm::Value *> Args = llvm::None) const; 1715 1716 /// Emits OpenMP-specific function prolog. 1717 /// Required for device constructs. 1718 virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D); 1719 1720 /// Gets the OpenMP-specific address of the local variable. 1721 virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, 1722 const VarDecl *VD); 1723 1724 /// Marks the declaration as already emitted for the device code and returns 1725 /// true, if it was marked already, and false, otherwise. 1726 bool markAsGlobalTarget(GlobalDecl GD); 1727 1728 /// Emit deferred declare target variables marked for deferred emission. 1729 void emitDeferredTargetDecls() const; 1730 1731 /// Adjust some parameters for the target-based directives, like addresses of 1732 /// the variables captured by reference in lambdas. 1733 virtual void 1734 adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, 1735 const OMPExecutableDirective &D) const; 1736 1737 /// Perform check on requires decl to ensure that target architecture 1738 /// supports unified addressing 1739 virtual void processRequiresDirective(const OMPRequiresDecl *D); 1740 1741 /// Gets default memory ordering as specified in requires directive. 1742 llvm::AtomicOrdering getDefaultMemoryOrdering() const; 1743 1744 /// Checks if the variable has associated OMPAllocateDeclAttr attribute with 1745 /// the predefined allocator and translates it into the corresponding address 1746 /// space. 1747 virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS); 1748 1749 /// Return whether the unified_shared_memory has been specified. 1750 bool hasRequiresUnifiedSharedMemory() const; 1751 1752 /// Checks if the \p VD variable is marked as nontemporal declaration in 1753 /// current context. 1754 bool isNontemporalDecl(const ValueDecl *VD) const; 1755 1756 /// Create specialized alloca to handle lastprivate conditionals. 1757 Address emitLastprivateConditionalInit(CodeGenFunction &CGF, 1758 const VarDecl *VD); 1759 1760 /// Checks if the provided \p LVal is lastprivate conditional and emits the 1761 /// code to update the value of the original variable. 1762 /// \code 1763 /// lastprivate(conditional: a) 1764 /// ... 1765 /// <type> a; 1766 /// lp_a = ...; 1767 /// #pragma omp critical(a) 1768 /// if (last_iv_a <= iv) { 1769 /// last_iv_a = iv; 1770 /// global_a = lp_a; 1771 /// } 1772 /// \endcode 1773 virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, 1774 const Expr *LHS); 1775 1776 /// Checks if the lastprivate conditional was updated in inner region and 1777 /// writes the value. 1778 /// \code 1779 /// lastprivate(conditional: a) 1780 /// ... 1781 /// <type> a;bool Fired = false; 1782 /// #pragma omp ... shared(a) 1783 /// { 1784 /// lp_a = ...; 1785 /// Fired = true; 1786 /// } 1787 /// if (Fired) { 1788 /// #pragma omp critical(a) 1789 /// if (last_iv_a <= iv) { 1790 /// last_iv_a = iv; 1791 /// global_a = lp_a; 1792 /// } 1793 /// Fired = false; 1794 /// } 1795 /// \endcode 1796 virtual void checkAndEmitSharedLastprivateConditional( 1797 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1798 const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls); 1799 1800 /// Gets the address of the global copy used for lastprivate conditional 1801 /// update, if any. 1802 /// \param PrivLVal LValue for the private copy. 1803 /// \param VD Original lastprivate declaration. 1804 virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, 1805 LValue PrivLVal, 1806 const VarDecl *VD, 1807 SourceLocation Loc); 1808 1809 /// Emits list of dependecies based on the provided data (array of 1810 /// dependence/expression pairs). 1811 /// \returns Pointer to the first element of the array casted to VoidPtr type. 1812 std::pair<llvm::Value *, Address> 1813 emitDependClause(CodeGenFunction &CGF, 1814 ArrayRef<OMPTaskDataTy::DependData> Dependencies, 1815 SourceLocation Loc); 1816 1817 /// Emits list of dependecies based on the provided data (array of 1818 /// dependence/expression pairs) for depobj construct. In this case, the 1819 /// variable is allocated in dynamically. \returns Pointer to the first 1820 /// element of the array casted to VoidPtr type. 1821 Address emitDepobjDependClause(CodeGenFunction &CGF, 1822 const OMPTaskDataTy::DependData &Dependencies, 1823 SourceLocation Loc); 1824 1825 /// Emits the code to destroy the dependency object provided in depobj 1826 /// directive. 1827 void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, 1828 SourceLocation Loc); 1829 1830 /// Updates the dependency kind in the specified depobj object. 1831 /// \param DepobjLVal LValue for the main depobj object. 1832 /// \param NewDepKind New dependency kind. 1833 void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, 1834 OpenMPDependClauseKind NewDepKind, SourceLocation Loc); 1835 1836 /// Initializes user defined allocators specified in the uses_allocators 1837 /// clauses. 1838 void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator, 1839 const Expr *AllocatorTraits); 1840 1841 /// Destroys user defined allocators specified in the uses_allocators clause. 1842 void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator); 1843 }; 1844 1845 /// Class supports emissionof SIMD-only code. 1846 class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { 1847 public: 1848 explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} 1849 ~CGOpenMPSIMDRuntime() override {} 1850 1851 /// Emits outlined function for the specified OpenMP parallel directive 1852 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1853 /// kmp_int32 BoundID, struct context_vars*). 1854 /// \param D OpenMP directive. 1855 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1856 /// \param InnermostKind Kind of innermost directive (for simple directives it 1857 /// is a directive itself, for combined - its innermost directive). 1858 /// \param CodeGen Code generation sequence for the \a D directive. 1859 llvm::Function * 1860 emitParallelOutlinedFunction(const OMPExecutableDirective &D, 1861 const VarDecl *ThreadIDVar, 1862 OpenMPDirectiveKind InnermostKind, 1863 const RegionCodeGenTy &CodeGen) override; 1864 1865 /// Emits outlined function for the specified OpenMP teams directive 1866 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1867 /// kmp_int32 BoundID, struct context_vars*). 1868 /// \param D OpenMP directive. 1869 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1870 /// \param InnermostKind Kind of innermost directive (for simple directives it 1871 /// is a directive itself, for combined - its innermost directive). 1872 /// \param CodeGen Code generation sequence for the \a D directive. 1873 llvm::Function * 1874 emitTeamsOutlinedFunction(const OMPExecutableDirective &D, 1875 const VarDecl *ThreadIDVar, 1876 OpenMPDirectiveKind InnermostKind, 1877 const RegionCodeGenTy &CodeGen) override; 1878 1879 /// Emits outlined function for the OpenMP task directive \a D. This 1880 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 1881 /// TaskT). 1882 /// \param D OpenMP directive. 1883 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1884 /// \param PartIDVar Variable for partition id in the current OpenMP untied 1885 /// task region. 1886 /// \param TaskTVar Variable for task_t argument. 1887 /// \param InnermostKind Kind of innermost directive (for simple directives it 1888 /// is a directive itself, for combined - its innermost directive). 1889 /// \param CodeGen Code generation sequence for the \a D directive. 1890 /// \param Tied true if task is generated for tied task, false otherwise. 1891 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 1892 /// tasks. 1893 /// 1894 llvm::Function *emitTaskOutlinedFunction( 1895 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1896 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 1897 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1898 bool Tied, unsigned &NumberOfParts) override; 1899 1900 /// Emits code for parallel or serial call of the \a OutlinedFn with 1901 /// variables captured in a record which address is stored in \a 1902 /// CapturedStruct. 1903 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 1904 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1905 /// \param CapturedVars A pointer to the record with the references to 1906 /// variables used in \a OutlinedFn function. 1907 /// \param IfCond Condition in the associated 'if' clause, if it was 1908 /// specified, nullptr otherwise. 1909 /// 1910 void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 1911 llvm::Function *OutlinedFn, 1912 ArrayRef<llvm::Value *> CapturedVars, 1913 const Expr *IfCond) override; 1914 1915 /// Emits a critical region. 1916 /// \param CriticalName Name of the critical region. 1917 /// \param CriticalOpGen Generator for the statement associated with the given 1918 /// critical region. 1919 /// \param Hint Value of the 'hint' clause (optional). 1920 void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 1921 const RegionCodeGenTy &CriticalOpGen, 1922 SourceLocation Loc, 1923 const Expr *Hint = nullptr) override; 1924 1925 /// Emits a master region. 1926 /// \param MasterOpGen Generator for the statement associated with the given 1927 /// master region. 1928 void emitMasterRegion(CodeGenFunction &CGF, 1929 const RegionCodeGenTy &MasterOpGen, 1930 SourceLocation Loc) override; 1931 1932 /// Emits code for a taskyield directive. 1933 void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; 1934 1935 /// Emit a taskgroup region. 1936 /// \param TaskgroupOpGen Generator for the statement associated with the 1937 /// given taskgroup region. 1938 void emitTaskgroupRegion(CodeGenFunction &CGF, 1939 const RegionCodeGenTy &TaskgroupOpGen, 1940 SourceLocation Loc) override; 1941 1942 /// Emits a single region. 1943 /// \param SingleOpGen Generator for the statement associated with the given 1944 /// single region. 1945 void emitSingleRegion(CodeGenFunction &CGF, 1946 const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, 1947 ArrayRef<const Expr *> CopyprivateVars, 1948 ArrayRef<const Expr *> DestExprs, 1949 ArrayRef<const Expr *> SrcExprs, 1950 ArrayRef<const Expr *> AssignmentOps) override; 1951 1952 /// Emit an ordered region. 1953 /// \param OrderedOpGen Generator for the statement associated with the given 1954 /// ordered region. 1955 void emitOrderedRegion(CodeGenFunction &CGF, 1956 const RegionCodeGenTy &OrderedOpGen, 1957 SourceLocation Loc, bool IsThreads) override; 1958 1959 /// Emit an implicit/explicit barrier for OpenMP threads. 1960 /// \param Kind Directive for which this implicit barrier call must be 1961 /// generated. Must be OMPD_barrier for explicit barrier generation. 1962 /// \param EmitChecks true if need to emit checks for cancellation barriers. 1963 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 1964 /// runtime class decides which one to emit (simple or with cancellation 1965 /// checks). 1966 /// 1967 void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 1968 OpenMPDirectiveKind Kind, bool EmitChecks = true, 1969 bool ForceSimpleCall = false) override; 1970 1971 /// This is used for non static scheduled types and when the ordered 1972 /// clause is present on the loop construct. 1973 /// Depending on the loop schedule, it is necessary to call some runtime 1974 /// routine before start of the OpenMP loop to get the loop upper / lower 1975 /// bounds \a LB and \a UB and stride \a ST. 1976 /// 1977 /// \param CGF Reference to current CodeGenFunction. 1978 /// \param Loc Clang source location. 1979 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1980 /// \param IVSize Size of the iteration variable in bits. 1981 /// \param IVSigned Sign of the iteration variable. 1982 /// \param Ordered true if loop is ordered, false otherwise. 1983 /// \param DispatchValues struct containing llvm values for lower bound, upper 1984 /// bound, and chunk expression. 1985 /// For the default (nullptr) value, the chunk 1 will be used. 1986 /// 1987 void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 1988 const OpenMPScheduleTy &ScheduleKind, 1989 unsigned IVSize, bool IVSigned, bool Ordered, 1990 const DispatchRTInput &DispatchValues) override; 1991 1992 /// Call the appropriate runtime routine to initialize it before start 1993 /// of loop. 1994 /// 1995 /// This is used only in case of static schedule, when the user did not 1996 /// specify a ordered clause on the loop construct. 1997 /// Depending on the loop schedule, it is necessary to call some runtime 1998 /// routine before start of the OpenMP loop to get the loop upper / lower 1999 /// bounds LB and UB and stride ST. 2000 /// 2001 /// \param CGF Reference to current CodeGenFunction. 2002 /// \param Loc Clang source location. 2003 /// \param DKind Kind of the directive. 2004 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 2005 /// \param Values Input arguments for the construct. 2006 /// 2007 void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 2008 OpenMPDirectiveKind DKind, 2009 const OpenMPScheduleTy &ScheduleKind, 2010 const StaticRTInput &Values) override; 2011 2012 /// 2013 /// \param CGF Reference to current CodeGenFunction. 2014 /// \param Loc Clang source location. 2015 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 2016 /// \param Values Input arguments for the construct. 2017 /// 2018 void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 2019 OpenMPDistScheduleClauseKind SchedKind, 2020 const StaticRTInput &Values) override; 2021 2022 /// Call the appropriate runtime routine to notify that we finished 2023 /// iteration of the ordered loop with the dynamic scheduling. 2024 /// 2025 /// \param CGF Reference to current CodeGenFunction. 2026 /// \param Loc Clang source location. 2027 /// \param IVSize Size of the iteration variable in bits. 2028 /// \param IVSigned Sign of the iteration variable. 2029 /// 2030 void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, 2031 unsigned IVSize, bool IVSigned) override; 2032 2033 /// Call the appropriate runtime routine to notify that we finished 2034 /// all the work with current loop. 2035 /// 2036 /// \param CGF Reference to current CodeGenFunction. 2037 /// \param Loc Clang source location. 2038 /// \param DKind Kind of the directive for which the static finish is emitted. 2039 /// 2040 void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 2041 OpenMPDirectiveKind DKind) override; 2042 2043 /// Call __kmpc_dispatch_next( 2044 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 2045 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 2046 /// kmp_int[32|64] *p_stride); 2047 /// \param IVSize Size of the iteration variable in bits. 2048 /// \param IVSigned Sign of the iteration variable. 2049 /// \param IL Address of the output variable in which the flag of the 2050 /// last iteration is returned. 2051 /// \param LB Address of the output variable in which the lower iteration 2052 /// number is returned. 2053 /// \param UB Address of the output variable in which the upper iteration 2054 /// number is returned. 2055 /// \param ST Address of the output variable in which the stride value is 2056 /// returned. 2057 llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 2058 unsigned IVSize, bool IVSigned, Address IL, 2059 Address LB, Address UB, Address ST) override; 2060 2061 /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 2062 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 2063 /// clause. 2064 /// \param NumThreads An integer value of threads. 2065 void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, 2066 SourceLocation Loc) override; 2067 2068 /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 2069 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 2070 void emitProcBindClause(CodeGenFunction &CGF, 2071 llvm::omp::ProcBindKind ProcBind, 2072 SourceLocation Loc) override; 2073 2074 /// Returns address of the threadprivate variable for the current 2075 /// thread. 2076 /// \param VD Threadprivate variable. 2077 /// \param VDAddr Address of the global variable \a VD. 2078 /// \param Loc Location of the reference to threadprivate var. 2079 /// \return Address of the threadprivate variable for the current thread. 2080 Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, 2081 Address VDAddr, SourceLocation Loc) override; 2082 2083 /// Emit a code for initialization of threadprivate variable. It emits 2084 /// a call to runtime library which adds initial value to the newly created 2085 /// threadprivate variable (if it is not constant) and registers destructor 2086 /// for the variable (if any). 2087 /// \param VD Threadprivate variable. 2088 /// \param VDAddr Address of the global variable \a VD. 2089 /// \param Loc Location of threadprivate declaration. 2090 /// \param PerformInit true if initialization expression is not constant. 2091 llvm::Function * 2092 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 2093 SourceLocation Loc, bool PerformInit, 2094 CodeGenFunction *CGF = nullptr) override; 2095 2096 /// Creates artificial threadprivate variable with name \p Name and type \p 2097 /// VarType. 2098 /// \param VarType Type of the artificial threadprivate variable. 2099 /// \param Name Name of the artificial threadprivate variable. 2100 Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 2101 QualType VarType, 2102 StringRef Name) override; 2103 2104 /// Emit flush of the variables specified in 'omp flush' directive. 2105 /// \param Vars List of variables to flush. 2106 void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 2107 SourceLocation Loc, llvm::AtomicOrdering AO) override; 2108 2109 /// Emit task region for the task directive. The task region is 2110 /// emitted in several steps: 2111 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 2112 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 2113 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 2114 /// function: 2115 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 2116 /// TaskFunction(gtid, tt->part_id, tt->shareds); 2117 /// return 0; 2118 /// } 2119 /// 2. Copy a list of shared variables to field shareds of the resulting 2120 /// structure kmp_task_t returned by the previous call (if any). 2121 /// 3. Copy a pointer to destructions function to field destructions of the 2122 /// resulting structure kmp_task_t. 2123 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 2124 /// kmp_task_t *new_task), where new_task is a resulting structure from 2125 /// previous items. 2126 /// \param D Current task directive. 2127 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 2128 /// /*part_id*/, captured_struct */*__context*/); 2129 /// \param SharedsTy A type which contains references the shared variables. 2130 /// \param Shareds Context with the list of shared variables from the \p 2131 /// TaskFunction. 2132 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 2133 /// otherwise. 2134 /// \param Data Additional data for task generation like tiednsee, final 2135 /// state, list of privates etc. 2136 void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 2137 const OMPExecutableDirective &D, 2138 llvm::Function *TaskFunction, QualType SharedsTy, 2139 Address Shareds, const Expr *IfCond, 2140 const OMPTaskDataTy &Data) override; 2141 2142 /// Emit task region for the taskloop directive. The taskloop region is 2143 /// emitted in several steps: 2144 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 2145 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 2146 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 2147 /// function: 2148 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 2149 /// TaskFunction(gtid, tt->part_id, tt->shareds); 2150 /// return 0; 2151 /// } 2152 /// 2. Copy a list of shared variables to field shareds of the resulting 2153 /// structure kmp_task_t returned by the previous call (if any). 2154 /// 3. Copy a pointer to destructions function to field destructions of the 2155 /// resulting structure kmp_task_t. 2156 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 2157 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 2158 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 2159 /// is a resulting structure from 2160 /// previous items. 2161 /// \param D Current task directive. 2162 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 2163 /// /*part_id*/, captured_struct */*__context*/); 2164 /// \param SharedsTy A type which contains references the shared variables. 2165 /// \param Shareds Context with the list of shared variables from the \p 2166 /// TaskFunction. 2167 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 2168 /// otherwise. 2169 /// \param Data Additional data for task generation like tiednsee, final 2170 /// state, list of privates etc. 2171 void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 2172 const OMPLoopDirective &D, llvm::Function *TaskFunction, 2173 QualType SharedsTy, Address Shareds, const Expr *IfCond, 2174 const OMPTaskDataTy &Data) override; 2175 2176 /// Emit a code for reduction clause. Next code should be emitted for 2177 /// reduction: 2178 /// \code 2179 /// 2180 /// static kmp_critical_name lock = { 0 }; 2181 /// 2182 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 2183 /// ... 2184 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 2185 /// ... 2186 /// } 2187 /// 2188 /// ... 2189 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 2190 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 2191 /// RedList, reduce_func, &<lock>)) { 2192 /// case 1: 2193 /// ... 2194 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 2195 /// ... 2196 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 2197 /// break; 2198 /// case 2: 2199 /// ... 2200 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 2201 /// ... 2202 /// break; 2203 /// default:; 2204 /// } 2205 /// \endcode 2206 /// 2207 /// \param Privates List of private copies for original reduction arguments. 2208 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 2209 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 2210 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 2211 /// or 'operator binop(LHS, RHS)'. 2212 /// \param Options List of options for reduction codegen: 2213 /// WithNowait true if parent directive has also nowait clause, false 2214 /// otherwise. 2215 /// SimpleReduction Emit reduction operation only. Used for omp simd 2216 /// directive on the host. 2217 /// ReductionKind The kind of reduction to perform. 2218 void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 2219 ArrayRef<const Expr *> Privates, 2220 ArrayRef<const Expr *> LHSExprs, 2221 ArrayRef<const Expr *> RHSExprs, 2222 ArrayRef<const Expr *> ReductionOps, 2223 ReductionOptionsTy Options) override; 2224 2225 /// Emit a code for initialization of task reduction clause. Next code 2226 /// should be emitted for reduction: 2227 /// \code 2228 /// 2229 /// _taskred_item_t red_data[n]; 2230 /// ... 2231 /// red_data[i].shar = &shareds[i]; 2232 /// red_data[i].orig = &origs[i]; 2233 /// red_data[i].size = sizeof(origs[i]); 2234 /// red_data[i].f_init = (void*)RedInit<i>; 2235 /// red_data[i].f_fini = (void*)RedDest<i>; 2236 /// red_data[i].f_comb = (void*)RedOp<i>; 2237 /// red_data[i].flags = <Flag_i>; 2238 /// ... 2239 /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); 2240 /// \endcode 2241 /// For reduction clause with task modifier it emits the next call: 2242 /// \code 2243 /// 2244 /// _taskred_item_t red_data[n]; 2245 /// ... 2246 /// red_data[i].shar = &shareds[i]; 2247 /// red_data[i].orig = &origs[i]; 2248 /// red_data[i].size = sizeof(origs[i]); 2249 /// red_data[i].f_init = (void*)RedInit<i>; 2250 /// red_data[i].f_fini = (void*)RedDest<i>; 2251 /// red_data[i].f_comb = (void*)RedOp<i>; 2252 /// red_data[i].flags = <Flag_i>; 2253 /// ... 2254 /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, 2255 /// red_data); 2256 /// \endcode 2257 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 2258 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 2259 /// \param Data Additional data for task generation like tiedness, final 2260 /// state, list of privates, reductions etc. 2261 llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, 2262 ArrayRef<const Expr *> LHSExprs, 2263 ArrayRef<const Expr *> RHSExprs, 2264 const OMPTaskDataTy &Data) override; 2265 2266 /// Emits the following code for reduction clause with task modifier: 2267 /// \code 2268 /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); 2269 /// \endcode 2270 void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, 2271 bool IsWorksharingReduction) override; 2272 2273 /// Required to resolve existing problems in the runtime. Emits threadprivate 2274 /// variables to store the size of the VLAs/array sections for 2275 /// initializer/combiner/finalizer functions + emits threadprivate variable to 2276 /// store the pointer to the original reduction item for the custom 2277 /// initializer defined by declare reduction construct. 2278 /// \param RCG Allows to reuse an existing data for the reductions. 2279 /// \param N Reduction item for which fixups must be emitted. 2280 void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 2281 ReductionCodeGen &RCG, unsigned N) override; 2282 2283 /// Get the address of `void *` type of the privatue copy of the reduction 2284 /// item specified by the \p SharedLVal. 2285 /// \param ReductionsPtr Pointer to the reduction data returned by the 2286 /// emitTaskReductionInit function. 2287 /// \param SharedLVal Address of the original reduction item. 2288 Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 2289 llvm::Value *ReductionsPtr, 2290 LValue SharedLVal) override; 2291 2292 /// Emit code for 'taskwait' directive. 2293 void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override; 2294 2295 /// Emit code for 'cancellation point' construct. 2296 /// \param CancelRegion Region kind for which the cancellation point must be 2297 /// emitted. 2298 /// 2299 void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, 2300 OpenMPDirectiveKind CancelRegion) override; 2301 2302 /// Emit code for 'cancel' construct. 2303 /// \param IfCond Condition in the associated 'if' clause, if it was 2304 /// specified, nullptr otherwise. 2305 /// \param CancelRegion Region kind for which the cancel must be emitted. 2306 /// 2307 void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 2308 const Expr *IfCond, 2309 OpenMPDirectiveKind CancelRegion) override; 2310 2311 /// Emit outilined function for 'target' directive. 2312 /// \param D Directive to emit. 2313 /// \param ParentName Name of the function that encloses the target region. 2314 /// \param OutlinedFn Outlined function value to be defined by this call. 2315 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 2316 /// \param IsOffloadEntry True if the outlined function is an offload entry. 2317 /// \param CodeGen Code generation sequence for the \a D directive. 2318 /// An outlined function may not be an entry if, e.g. the if clause always 2319 /// evaluates to false. 2320 void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 2321 StringRef ParentName, 2322 llvm::Function *&OutlinedFn, 2323 llvm::Constant *&OutlinedFnID, 2324 bool IsOffloadEntry, 2325 const RegionCodeGenTy &CodeGen) override; 2326 2327 /// Emit the target offloading code associated with \a D. The emitted 2328 /// code attempts offloading the execution to the device, an the event of 2329 /// a failure it executes the host version outlined in \a OutlinedFn. 2330 /// \param D Directive to emit. 2331 /// \param OutlinedFn Host version of the code to be offloaded. 2332 /// \param OutlinedFnID ID of host version of the code to be offloaded. 2333 /// \param IfCond Expression evaluated in if clause associated with the target 2334 /// directive, or null if no if clause is used. 2335 /// \param Device Expression evaluated in device clause associated with the 2336 /// target directive, or null if no device clause is used and device modifier. 2337 void emitTargetCall( 2338 CodeGenFunction &CGF, const OMPExecutableDirective &D, 2339 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, 2340 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, 2341 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 2342 const OMPLoopDirective &D)> 2343 SizeEmitter) override; 2344 2345 /// Emit the target regions enclosed in \a GD function definition or 2346 /// the function itself in case it is a valid device function. Returns true if 2347 /// \a GD was dealt with successfully. 2348 /// \param GD Function to scan. 2349 bool emitTargetFunctions(GlobalDecl GD) override; 2350 2351 /// Emit the global variable if it is a valid device global variable. 2352 /// Returns true if \a GD was dealt with successfully. 2353 /// \param GD Variable declaration to emit. 2354 bool emitTargetGlobalVariable(GlobalDecl GD) override; 2355 2356 /// Emit the global \a GD if it is meaningful for the target. Returns 2357 /// if it was emitted successfully. 2358 /// \param GD Global to scan. 2359 bool emitTargetGlobal(GlobalDecl GD) override; 2360 2361 /// Emits code for teams call of the \a OutlinedFn with 2362 /// variables captured in a record which address is stored in \a 2363 /// CapturedStruct. 2364 /// \param OutlinedFn Outlined function to be run by team masters. Type of 2365 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 2366 /// \param CapturedVars A pointer to the record with the references to 2367 /// variables used in \a OutlinedFn function. 2368 /// 2369 void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, 2370 SourceLocation Loc, llvm::Function *OutlinedFn, 2371 ArrayRef<llvm::Value *> CapturedVars) override; 2372 2373 /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 2374 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 2375 /// for num_teams clause. 2376 /// \param NumTeams An integer expression of teams. 2377 /// \param ThreadLimit An integer expression of threads. 2378 void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 2379 const Expr *ThreadLimit, SourceLocation Loc) override; 2380 2381 /// Emit the target data mapping code associated with \a D. 2382 /// \param D Directive to emit. 2383 /// \param IfCond Expression evaluated in if clause associated with the 2384 /// target directive, or null if no device clause is used. 2385 /// \param Device Expression evaluated in device clause associated with the 2386 /// target directive, or null if no device clause is used. 2387 /// \param Info A record used to store information that needs to be preserved 2388 /// until the region is closed. 2389 void emitTargetDataCalls(CodeGenFunction &CGF, 2390 const OMPExecutableDirective &D, const Expr *IfCond, 2391 const Expr *Device, const RegionCodeGenTy &CodeGen, 2392 TargetDataInfo &Info) override; 2393 2394 /// Emit the data mapping/movement code associated with the directive 2395 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 2396 /// \param D Directive to emit. 2397 /// \param IfCond Expression evaluated in if clause associated with the target 2398 /// directive, or null if no if clause is used. 2399 /// \param Device Expression evaluated in device clause associated with the 2400 /// target directive, or null if no device clause is used. 2401 void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 2402 const OMPExecutableDirective &D, 2403 const Expr *IfCond, 2404 const Expr *Device) override; 2405 2406 /// Emit initialization for doacross loop nesting support. 2407 /// \param D Loop-based construct used in doacross nesting construct. 2408 void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, 2409 ArrayRef<Expr *> NumIterations) override; 2410 2411 /// Emit code for doacross ordered directive with 'depend' clause. 2412 /// \param C 'depend' clause with 'sink|source' dependency kind. 2413 void emitDoacrossOrdered(CodeGenFunction &CGF, 2414 const OMPDependClause *C) override; 2415 2416 /// Translates the native parameter of outlined function if this is required 2417 /// for target. 2418 /// \param FD Field decl from captured record for the parameter. 2419 /// \param NativeParam Parameter itself. 2420 const VarDecl *translateParameter(const FieldDecl *FD, 2421 const VarDecl *NativeParam) const override; 2422 2423 /// Gets the address of the native argument basing on the address of the 2424 /// target-specific parameter. 2425 /// \param NativeParam Parameter itself. 2426 /// \param TargetParam Corresponding target-specific parameter. 2427 Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, 2428 const VarDecl *TargetParam) const override; 2429 2430 /// Gets the OpenMP-specific address of the local variable. 2431 Address getAddressOfLocalVariable(CodeGenFunction &CGF, 2432 const VarDecl *VD) override { 2433 return Address::invalid(); 2434 } 2435 }; 2436 2437 } // namespace CodeGen 2438 } // namespace clang 2439 2440 #endif 2441