1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides a class for OpenMP runtime code generation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 15 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 16 17 #include "CGValue.h" 18 #include "clang/AST/Type.h" 19 #include "clang/Basic/OpenMPKinds.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/ValueHandle.h" 26 27 namespace llvm { 28 class ArrayType; 29 class Constant; 30 class FunctionType; 31 class GlobalVariable; 32 class StructType; 33 class Type; 34 class Value; 35 } // namespace llvm 36 37 namespace clang { 38 class Expr; 39 class GlobalDecl; 40 class OMPDependClause; 41 class OMPExecutableDirective; 42 class OMPLoopDirective; 43 class VarDecl; 44 class OMPDeclareReductionDecl; 45 class IdentifierInfo; 46 47 namespace CodeGen { 48 class Address; 49 class CodeGenFunction; 50 class CodeGenModule; 51 52 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP 53 /// region. 54 class PrePostActionTy { 55 public: 56 explicit PrePostActionTy() {} 57 virtual void Enter(CodeGenFunction &CGF) {} 58 virtual void Exit(CodeGenFunction &CGF) {} 59 virtual ~PrePostActionTy() {} 60 }; 61 62 /// Class provides a way to call simple version of codegen for OpenMP region, or 63 /// an advanced with possible pre|post-actions in codegen. 64 class RegionCodeGenTy final { 65 intptr_t CodeGen; 66 typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); 67 CodeGenTy Callback; 68 mutable PrePostActionTy *PrePostAction; 69 RegionCodeGenTy() = delete; 70 RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete; 71 template <typename Callable> 72 static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, 73 PrePostActionTy &Action) { 74 return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); 75 } 76 77 public: 78 template <typename Callable> 79 RegionCodeGenTy( 80 Callable &&CodeGen, 81 typename std::enable_if< 82 !std::is_same<typename std::remove_reference<Callable>::type, 83 RegionCodeGenTy>::value>::type * = nullptr) 84 : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), 85 Callback(CallbackFn<typename std::remove_reference<Callable>::type>), 86 PrePostAction(nullptr) {} 87 void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } 88 void operator()(CodeGenFunction &CGF) const; 89 }; 90 91 struct OMPTaskDataTy final { 92 SmallVector<const Expr *, 4> PrivateVars; 93 SmallVector<const Expr *, 4> PrivateCopies; 94 SmallVector<const Expr *, 4> FirstprivateVars; 95 SmallVector<const Expr *, 4> FirstprivateCopies; 96 SmallVector<const Expr *, 4> FirstprivateInits; 97 SmallVector<const Expr *, 4> LastprivateVars; 98 SmallVector<const Expr *, 4> LastprivateCopies; 99 SmallVector<const Expr *, 4> ReductionVars; 100 SmallVector<const Expr *, 4> ReductionCopies; 101 SmallVector<const Expr *, 4> ReductionOps; 102 SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 4> Dependences; 103 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 104 llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; 105 llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; 106 llvm::Value *Reductions = nullptr; 107 unsigned NumberOfParts = 0; 108 bool Tied = true; 109 bool Nogroup = false; 110 }; 111 112 /// Class intended to support codegen of all kind of the reduction clauses. 113 class ReductionCodeGen { 114 private: 115 /// Data required for codegen of reduction clauses. 116 struct ReductionData { 117 /// Reference to the original shared item. 118 const Expr *Ref = nullptr; 119 /// Helper expression for generation of private copy. 120 const Expr *Private = nullptr; 121 /// Helper expression for generation reduction operation. 122 const Expr *ReductionOp = nullptr; 123 ReductionData(const Expr *Ref, const Expr *Private, const Expr *ReductionOp) 124 : Ref(Ref), Private(Private), ReductionOp(ReductionOp) {} 125 }; 126 /// List of reduction-based clauses. 127 SmallVector<ReductionData, 4> ClausesData; 128 129 /// List of addresses of original shared variables/expressions. 130 SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; 131 /// Sizes of the reduction items in chars. 132 SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; 133 /// Base declarations for the reduction items. 134 SmallVector<const VarDecl *, 4> BaseDecls; 135 136 /// Emits lvalue for shared expresion. 137 LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); 138 /// Emits upper bound for shared expression (if array section). 139 LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); 140 /// Performs aggregate initialization. 141 /// \param N Number of reduction item in the common list. 142 /// \param PrivateAddr Address of the corresponding private item. 143 /// \param SharedLVal Address of the original shared variable. 144 /// \param DRD Declare reduction construct used for reduction item. 145 void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, 146 Address PrivateAddr, LValue SharedLVal, 147 const OMPDeclareReductionDecl *DRD); 148 149 public: 150 ReductionCodeGen(ArrayRef<const Expr *> Shareds, 151 ArrayRef<const Expr *> Privates, 152 ArrayRef<const Expr *> ReductionOps); 153 /// Emits lvalue for a reduction item. 154 /// \param N Number of the reduction item. 155 void emitSharedLValue(CodeGenFunction &CGF, unsigned N); 156 /// Emits the code for the variable-modified type, if required. 157 /// \param N Number of the reduction item. 158 void emitAggregateType(CodeGenFunction &CGF, unsigned N); 159 /// Emits the code for the variable-modified type, if required. 160 /// \param N Number of the reduction item. 161 /// \param Size Size of the type in chars. 162 void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); 163 /// Performs initialization of the private copy for the reduction item. 164 /// \param N Number of the reduction item. 165 /// \param PrivateAddr Address of the corresponding private item. 166 /// \param DefaultInit Default initialization sequence that should be 167 /// performed if no reduction specific initialization is found. 168 /// \param SharedLVal Address of the original shared variable. 169 void 170 emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, 171 LValue SharedLVal, 172 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); 173 /// Returns true if the private copy requires cleanups. 174 bool needCleanups(unsigned N); 175 /// Emits cleanup code for the reduction item. 176 /// \param N Number of the reduction item. 177 /// \param PrivateAddr Address of the corresponding private item. 178 void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); 179 /// Adjusts \p PrivatedAddr for using instead of the original variable 180 /// address in normal operations. 181 /// \param N Number of the reduction item. 182 /// \param PrivateAddr Address of the corresponding private item. 183 Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, 184 Address PrivateAddr); 185 /// Returns LValue for the reduction item. 186 LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } 187 /// Returns the size of the reduction item (in chars and total number of 188 /// elements in the item), or nullptr, if the size is a constant. 189 std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { 190 return Sizes[N]; 191 } 192 /// Returns the base declaration of the reduction item. 193 const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } 194 /// Returns true if the initialization of the reduction item uses initializer 195 /// from declare reduction construct. 196 bool usesReductionInitializer(unsigned N) const; 197 }; 198 199 class CGOpenMPRuntime { 200 protected: 201 CodeGenModule &CGM; 202 203 /// \brief Creates offloading entry for the provided entry ID \a ID, 204 /// address \a Addr, size \a Size, and flags \a Flags. 205 virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, 206 uint64_t Size, int32_t Flags = 0); 207 208 /// \brief Helper to emit outlined function for 'target' directive. 209 /// \param D Directive to emit. 210 /// \param ParentName Name of the function that encloses the target region. 211 /// \param OutlinedFn Outlined function value to be defined by this call. 212 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 213 /// \param IsOffloadEntry True if the outlined function is an offload entry. 214 /// \param CodeGen Lambda codegen specific to an accelerator device. 215 /// An outlined function may not be an entry if, e.g. the if clause always 216 /// evaluates to false. 217 virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, 218 StringRef ParentName, 219 llvm::Function *&OutlinedFn, 220 llvm::Constant *&OutlinedFnID, 221 bool IsOffloadEntry, 222 const RegionCodeGenTy &CodeGen); 223 224 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen 225 /// function. Here is the logic: 226 /// if (Cond) { 227 /// ThenGen(); 228 /// } else { 229 /// ElseGen(); 230 /// } 231 void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond, 232 const RegionCodeGenTy &ThenGen, 233 const RegionCodeGenTy &ElseGen); 234 235 /// \brief Emits object of ident_t type with info for source location. 236 /// \param Flags Flags for OpenMP location. 237 /// 238 llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, 239 unsigned Flags = 0); 240 241 /// \brief Returns pointer to ident_t type. 242 llvm::Type *getIdentTyPointerTy(); 243 244 /// \brief Gets thread id value for the current thread. 245 /// 246 llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); 247 248 /// \brief Get the function name of an outlined region. 249 // The name can be customized depending on the target. 250 // 251 virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } 252 253 /// Emits \p Callee function call with arguments \p Args with location \p Loc. 254 void emitCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *Callee, 255 ArrayRef<llvm::Value *> Args = llvm::None) const; 256 257 private: 258 /// \brief Default const ident_t object used for initialization of all other 259 /// ident_t objects. 260 llvm::Constant *DefaultOpenMPPSource = nullptr; 261 /// \brief Map of flags and corresponding default locations. 262 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDefaultLocMapTy; 263 OpenMPDefaultLocMapTy OpenMPDefaultLocMap; 264 Address getOrCreateDefaultLocation(unsigned Flags); 265 266 llvm::StructType *IdentTy = nullptr; 267 /// \brief Map for SourceLocation and OpenMP runtime library debug locations. 268 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy; 269 OpenMPDebugLocMapTy OpenMPDebugLocMap; 270 /// \brief The type for a microtask which gets passed to __kmpc_fork_call(). 271 /// Original representation is: 272 /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); 273 llvm::FunctionType *Kmpc_MicroTy = nullptr; 274 /// \brief Stores debug location and ThreadID for the function. 275 struct DebugLocThreadIdTy { 276 llvm::Value *DebugLoc; 277 llvm::Value *ThreadID; 278 }; 279 /// \brief Map of local debug location, ThreadId and functions. 280 typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> 281 OpenMPLocThreadIDMapTy; 282 OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; 283 /// Map of UDRs and corresponding combiner/initializer. 284 typedef llvm::DenseMap<const OMPDeclareReductionDecl *, 285 std::pair<llvm::Function *, llvm::Function *>> 286 UDRMapTy; 287 UDRMapTy UDRMap; 288 /// Map of functions and locally defined UDRs. 289 typedef llvm::DenseMap<llvm::Function *, 290 SmallVector<const OMPDeclareReductionDecl *, 4>> 291 FunctionUDRMapTy; 292 FunctionUDRMapTy FunctionUDRMap; 293 IdentifierInfo *In = nullptr; 294 IdentifierInfo *Out = nullptr; 295 IdentifierInfo *Priv = nullptr; 296 IdentifierInfo *Orig = nullptr; 297 /// \brief Type kmp_critical_name, originally defined as typedef kmp_int32 298 /// kmp_critical_name[8]; 299 llvm::ArrayType *KmpCriticalNameTy; 300 /// \brief An ordered map of auto-generated variables to their unique names. 301 /// It stores variables with the following names: 1) ".gomp_critical_user_" + 302 /// <critical_section_name> + ".var" for "omp critical" directives; 2) 303 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate 304 /// variables. 305 llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator> 306 InternalVars; 307 /// \brief Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); 308 llvm::Type *KmpRoutineEntryPtrTy = nullptr; 309 QualType KmpRoutineEntryPtrQTy; 310 /// \brief Type typedef struct kmp_task { 311 /// void * shareds; /**< pointer to block of pointers to 312 /// shared vars */ 313 /// kmp_routine_entry_t routine; /**< pointer to routine to call for 314 /// executing task */ 315 /// kmp_int32 part_id; /**< part id for the task */ 316 /// kmp_routine_entry_t destructors; /* pointer to function to invoke 317 /// deconstructors of firstprivate C++ objects */ 318 /// } kmp_task_t; 319 QualType KmpTaskTQTy; 320 /// Saved kmp_task_t for task directive. 321 QualType SavedKmpTaskTQTy; 322 /// Saved kmp_task_t for taskloop-based directive. 323 QualType SavedKmpTaskloopTQTy; 324 /// \brief Type typedef struct kmp_depend_info { 325 /// kmp_intptr_t base_addr; 326 /// size_t len; 327 /// struct { 328 /// bool in:1; 329 /// bool out:1; 330 /// } flags; 331 /// } kmp_depend_info_t; 332 QualType KmpDependInfoTy; 333 /// struct kmp_dim { // loop bounds info casted to kmp_int64 334 /// kmp_int64 lo; // lower 335 /// kmp_int64 up; // upper 336 /// kmp_int64 st; // stride 337 /// }; 338 QualType KmpDimTy; 339 /// \brief Type struct __tgt_offload_entry{ 340 /// void *addr; // Pointer to the offload entry info. 341 /// // (function or global) 342 /// char *name; // Name of the function or global. 343 /// size_t size; // Size of the entry info (0 if it a function). 344 /// }; 345 QualType TgtOffloadEntryQTy; 346 /// struct __tgt_device_image{ 347 /// void *ImageStart; // Pointer to the target code start. 348 /// void *ImageEnd; // Pointer to the target code end. 349 /// // We also add the host entries to the device image, as it may be useful 350 /// // for the target runtime to have access to that information. 351 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all 352 /// // the entries. 353 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the 354 /// // entries (non inclusive). 355 /// }; 356 QualType TgtDeviceImageQTy; 357 /// struct __tgt_bin_desc{ 358 /// int32_t NumDevices; // Number of devices supported. 359 /// __tgt_device_image *DeviceImages; // Arrays of device images 360 /// // (one per device). 361 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all the 362 /// // entries. 363 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the 364 /// // entries (non inclusive). 365 /// }; 366 QualType TgtBinaryDescriptorQTy; 367 /// \brief Entity that registers the offloading constants that were emitted so 368 /// far. 369 class OffloadEntriesInfoManagerTy { 370 CodeGenModule &CGM; 371 372 /// \brief Number of entries registered so far. 373 unsigned OffloadingEntriesNum; 374 375 public: 376 /// Base class of the entries info. 377 class OffloadEntryInfo { 378 public: 379 /// Kind of a given entry. Currently, only target regions are 380 /// supported. 381 enum OffloadingEntryInfoKinds : unsigned { 382 // Entry is a target region. 383 OFFLOAD_ENTRY_INFO_TARGET_REGION = 0, 384 // Invalid entry info. 385 OFFLOAD_ENTRY_INFO_INVALID = ~0u 386 }; 387 388 OffloadEntryInfo() 389 : Flags(0), Order(~0u), Kind(OFFLOAD_ENTRY_INFO_INVALID) {} 390 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, 391 int32_t Flags) 392 : Flags(Flags), Order(Order), Kind(Kind) {} 393 394 bool isValid() const { return Order != ~0u; } 395 unsigned getOrder() const { return Order; } 396 OffloadingEntryInfoKinds getKind() const { return Kind; } 397 int32_t getFlags() const { return Flags; } 398 void setFlags(int32_t NewFlags) { Flags = NewFlags; } 399 static bool classof(const OffloadEntryInfo *Info) { return true; } 400 401 private: 402 /// Flags associated with the device global. 403 int32_t Flags; 404 405 /// Order this entry was emitted. 406 unsigned Order; 407 408 OffloadingEntryInfoKinds Kind; 409 }; 410 411 /// \brief Return true if a there are no entries defined. 412 bool empty() const; 413 /// \brief Return number of entries defined so far. 414 unsigned size() const { return OffloadingEntriesNum; } 415 OffloadEntriesInfoManagerTy(CodeGenModule &CGM) 416 : CGM(CGM), OffloadingEntriesNum(0) {} 417 418 /// 419 /// Target region entries related. 420 /// 421 /// \brief Target region entries info. 422 class OffloadEntryInfoTargetRegion : public OffloadEntryInfo { 423 // \brief Address of the entity that has to be mapped for offloading. 424 llvm::Constant *Addr; 425 // \brief Address that can be used as the ID of the entry. 426 llvm::Constant *ID; 427 428 public: 429 OffloadEntryInfoTargetRegion() 430 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, ~0u, 431 /*Flags=*/0), 432 Addr(nullptr), ID(nullptr) {} 433 explicit OffloadEntryInfoTargetRegion(unsigned Order, 434 llvm::Constant *Addr, 435 llvm::Constant *ID, int32_t Flags) 436 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, Order, Flags), 437 Addr(Addr), ID(ID) {} 438 439 llvm::Constant *getAddress() const { return Addr; } 440 llvm::Constant *getID() const { return ID; } 441 void setAddress(llvm::Constant *V) { 442 assert(!Addr && "Address as been set before!"); 443 Addr = V; 444 } 445 void setID(llvm::Constant *V) { 446 assert(!ID && "ID as been set before!"); 447 ID = V; 448 } 449 static bool classof(const OffloadEntryInfo *Info) { 450 return Info->getKind() == OFFLOAD_ENTRY_INFO_TARGET_REGION; 451 } 452 }; 453 /// \brief Initialize target region entry. 454 void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 455 StringRef ParentName, unsigned LineNum, 456 unsigned Order); 457 /// \brief Register target region entry. 458 void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 459 StringRef ParentName, unsigned LineNum, 460 llvm::Constant *Addr, llvm::Constant *ID, 461 int32_t Flags); 462 /// \brief Return true if a target region entry with the provided 463 /// information exists. 464 bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 465 StringRef ParentName, unsigned LineNum) const; 466 /// brief Applies action \a Action on all registered entries. 467 typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, 468 OffloadEntryInfoTargetRegion &)> 469 OffloadTargetRegionEntryInfoActTy; 470 void actOnTargetRegionEntriesInfo( 471 const OffloadTargetRegionEntryInfoActTy &Action); 472 473 private: 474 // Storage for target region entries kind. The storage is to be indexed by 475 // file ID, device ID, parent function name and line number. 476 typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> 477 OffloadEntriesTargetRegionPerLine; 478 typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> 479 OffloadEntriesTargetRegionPerParentName; 480 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> 481 OffloadEntriesTargetRegionPerFile; 482 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> 483 OffloadEntriesTargetRegionPerDevice; 484 typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; 485 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; 486 }; 487 OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; 488 489 /// \brief Creates and registers offloading binary descriptor for the current 490 /// compilation unit. The function that does the registration is returned. 491 llvm::Function *createOffloadingBinaryDescriptorRegistration(); 492 493 /// \brief Creates all the offload entries in the current compilation unit 494 /// along with the associated metadata. 495 void createOffloadEntriesAndInfoMetadata(); 496 497 /// \brief Loads all the offload entries information from the host IR 498 /// metadata. 499 void loadOffloadInfoMetadata(); 500 501 /// \brief Returns __tgt_offload_entry type. 502 QualType getTgtOffloadEntryQTy(); 503 504 /// \brief Returns __tgt_device_image type. 505 QualType getTgtDeviceImageQTy(); 506 507 /// \brief Returns __tgt_bin_desc type. 508 QualType getTgtBinaryDescriptorQTy(); 509 510 /// \brief Start scanning from statement \a S and and emit all target regions 511 /// found along the way. 512 /// \param S Starting statement. 513 /// \param ParentName Name of the function declaration that is being scanned. 514 void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); 515 516 /// \brief Build type kmp_routine_entry_t (if not built yet). 517 void emitKmpRoutineEntryT(QualType KmpInt32Ty); 518 519 /// \brief Returns pointer to kmpc_micro type. 520 llvm::Type *getKmpc_MicroPointerTy(); 521 522 /// \brief Returns specified OpenMP runtime function. 523 /// \param Function OpenMP runtime function. 524 /// \return Specified function. 525 llvm::Constant *createRuntimeFunction(unsigned Function); 526 527 /// \brief Returns __kmpc_for_static_init_* runtime function for the specified 528 /// size \a IVSize and sign \a IVSigned. 529 llvm::Constant *createForStaticInitFunction(unsigned IVSize, bool IVSigned); 530 531 /// \brief Returns __kmpc_dispatch_init_* runtime function for the specified 532 /// size \a IVSize and sign \a IVSigned. 533 llvm::Constant *createDispatchInitFunction(unsigned IVSize, bool IVSigned); 534 535 /// \brief Returns __kmpc_dispatch_next_* runtime function for the specified 536 /// size \a IVSize and sign \a IVSigned. 537 llvm::Constant *createDispatchNextFunction(unsigned IVSize, bool IVSigned); 538 539 /// \brief Returns __kmpc_dispatch_fini_* runtime function for the specified 540 /// size \a IVSize and sign \a IVSigned. 541 llvm::Constant *createDispatchFiniFunction(unsigned IVSize, bool IVSigned); 542 543 /// \brief If the specified mangled name is not in the module, create and 544 /// return threadprivate cache object. This object is a pointer's worth of 545 /// storage that's reserved for use by the OpenMP runtime. 546 /// \param VD Threadprivate variable. 547 /// \return Cache variable for the specified threadprivate. 548 llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); 549 550 /// \brief Emits address of the word in a memory where current thread id is 551 /// stored. 552 virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); 553 554 /// \brief Gets (if variable with the given name already exist) or creates 555 /// internal global variable with the specified Name. The created variable has 556 /// linkage CommonLinkage by default and is initialized by null value. 557 /// \param Ty Type of the global variable. If it is exist already the type 558 /// must be the same. 559 /// \param Name Name of the variable. 560 llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty, 561 const llvm::Twine &Name); 562 563 /// \brief Set of threadprivate variables with the generated initializer. 564 llvm::SmallPtrSet<const VarDecl *, 4> ThreadPrivateWithDefinition; 565 566 /// \brief Emits initialization code for the threadprivate variables. 567 /// \param VDAddr Address of the global variable \a VD. 568 /// \param Ctor Pointer to a global init function for \a VD. 569 /// \param CopyCtor Pointer to a global copy function for \a VD. 570 /// \param Dtor Pointer to a global destructor function for \a VD. 571 /// \param Loc Location of threadprivate declaration. 572 void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, 573 llvm::Value *Ctor, llvm::Value *CopyCtor, 574 llvm::Value *Dtor, SourceLocation Loc); 575 576 /// \brief Returns corresponding lock object for the specified critical region 577 /// name. If the lock object does not exist it is created, otherwise the 578 /// reference to the existing copy is returned. 579 /// \param CriticalName Name of the critical region. 580 /// 581 llvm::Value *getCriticalRegionLock(StringRef CriticalName); 582 583 struct TaskResultTy { 584 llvm::Value *NewTask = nullptr; 585 llvm::Value *TaskEntry = nullptr; 586 llvm::Value *NewTaskNewTaskTTy = nullptr; 587 LValue TDBase; 588 RecordDecl *KmpTaskTQTyRD = nullptr; 589 llvm::Value *TaskDupFn = nullptr; 590 }; 591 /// Emit task region for the task directive. The task region is emitted in 592 /// several steps: 593 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 594 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 595 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 596 /// function: 597 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 598 /// TaskFunction(gtid, tt->part_id, tt->shareds); 599 /// return 0; 600 /// } 601 /// 2. Copy a list of shared variables to field shareds of the resulting 602 /// structure kmp_task_t returned by the previous call (if any). 603 /// 3. Copy a pointer to destructions function to field destructions of the 604 /// resulting structure kmp_task_t. 605 /// \param D Current task directive. 606 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 607 /// /*part_id*/, captured_struct */*__context*/); 608 /// \param SharedsTy A type which contains references the shared variables. 609 /// \param Shareds Context with the list of shared variables from the \p 610 /// TaskFunction. 611 /// \param Data Additional data for task generation like tiednsee, final 612 /// state, list of privates etc. 613 TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, 614 const OMPExecutableDirective &D, 615 llvm::Value *TaskFunction, QualType SharedsTy, 616 Address Shareds, const OMPTaskDataTy &Data); 617 618 public: 619 explicit CGOpenMPRuntime(CodeGenModule &CGM); 620 virtual ~CGOpenMPRuntime() {} 621 virtual void clear(); 622 623 /// Emit code for the specified user defined reduction construct. 624 virtual void emitUserDefinedReduction(CodeGenFunction *CGF, 625 const OMPDeclareReductionDecl *D); 626 /// Get combiner/initializer for the specified user-defined reduction, if any. 627 virtual std::pair<llvm::Function *, llvm::Function *> 628 getUserDefinedReduction(const OMPDeclareReductionDecl *D); 629 630 /// \brief Emits outlined function for the specified OpenMP parallel directive 631 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 632 /// kmp_int32 BoundID, struct context_vars*). 633 /// \param D OpenMP directive. 634 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 635 /// \param InnermostKind Kind of innermost directive (for simple directives it 636 /// is a directive itself, for combined - its innermost directive). 637 /// \param CodeGen Code generation sequence for the \a D directive. 638 virtual llvm::Value *emitParallelOutlinedFunction( 639 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 640 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 641 642 /// \brief Emits outlined function for the specified OpenMP teams directive 643 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 644 /// kmp_int32 BoundID, struct context_vars*). 645 /// \param D OpenMP directive. 646 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 647 /// \param InnermostKind Kind of innermost directive (for simple directives it 648 /// is a directive itself, for combined - its innermost directive). 649 /// \param CodeGen Code generation sequence for the \a D directive. 650 virtual llvm::Value *emitTeamsOutlinedFunction( 651 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 652 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 653 654 /// \brief Emits outlined function for the OpenMP task directive \a D. This 655 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 656 /// TaskT). 657 /// \param D OpenMP directive. 658 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 659 /// \param PartIDVar Variable for partition id in the current OpenMP untied 660 /// task region. 661 /// \param TaskTVar Variable for task_t argument. 662 /// \param InnermostKind Kind of innermost directive (for simple directives it 663 /// is a directive itself, for combined - its innermost directive). 664 /// \param CodeGen Code generation sequence for the \a D directive. 665 /// \param Tied true if task is generated for tied task, false otherwise. 666 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 667 /// tasks. 668 /// 669 virtual llvm::Value *emitTaskOutlinedFunction( 670 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 671 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 672 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 673 bool Tied, unsigned &NumberOfParts); 674 675 /// \brief Cleans up references to the objects in finished function. 676 /// 677 void functionFinished(CodeGenFunction &CGF); 678 679 /// \brief Emits code for parallel or serial call of the \a OutlinedFn with 680 /// variables captured in a record which address is stored in \a 681 /// CapturedStruct. 682 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 683 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 684 /// \param CapturedVars A pointer to the record with the references to 685 /// variables used in \a OutlinedFn function. 686 /// \param IfCond Condition in the associated 'if' clause, if it was 687 /// specified, nullptr otherwise. 688 /// 689 virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 690 llvm::Value *OutlinedFn, 691 ArrayRef<llvm::Value *> CapturedVars, 692 const Expr *IfCond); 693 694 /// \brief Emits a critical region. 695 /// \param CriticalName Name of the critical region. 696 /// \param CriticalOpGen Generator for the statement associated with the given 697 /// critical region. 698 /// \param Hint Value of the 'hint' clause (optional). 699 virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 700 const RegionCodeGenTy &CriticalOpGen, 701 SourceLocation Loc, 702 const Expr *Hint = nullptr); 703 704 /// \brief Emits a master region. 705 /// \param MasterOpGen Generator for the statement associated with the given 706 /// master region. 707 virtual void emitMasterRegion(CodeGenFunction &CGF, 708 const RegionCodeGenTy &MasterOpGen, 709 SourceLocation Loc); 710 711 /// \brief Emits code for a taskyield directive. 712 virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); 713 714 /// \brief Emit a taskgroup region. 715 /// \param TaskgroupOpGen Generator for the statement associated with the 716 /// given taskgroup region. 717 virtual void emitTaskgroupRegion(CodeGenFunction &CGF, 718 const RegionCodeGenTy &TaskgroupOpGen, 719 SourceLocation Loc); 720 721 /// \brief Emits a single region. 722 /// \param SingleOpGen Generator for the statement associated with the given 723 /// single region. 724 virtual void emitSingleRegion(CodeGenFunction &CGF, 725 const RegionCodeGenTy &SingleOpGen, 726 SourceLocation Loc, 727 ArrayRef<const Expr *> CopyprivateVars, 728 ArrayRef<const Expr *> DestExprs, 729 ArrayRef<const Expr *> SrcExprs, 730 ArrayRef<const Expr *> AssignmentOps); 731 732 /// \brief Emit an ordered region. 733 /// \param OrderedOpGen Generator for the statement associated with the given 734 /// ordered region. 735 virtual void emitOrderedRegion(CodeGenFunction &CGF, 736 const RegionCodeGenTy &OrderedOpGen, 737 SourceLocation Loc, bool IsThreads); 738 739 /// \brief Emit an implicit/explicit barrier for OpenMP threads. 740 /// \param Kind Directive for which this implicit barrier call must be 741 /// generated. Must be OMPD_barrier for explicit barrier generation. 742 /// \param EmitChecks true if need to emit checks for cancellation barriers. 743 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 744 /// runtime class decides which one to emit (simple or with cancellation 745 /// checks). 746 /// 747 virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 748 OpenMPDirectiveKind Kind, 749 bool EmitChecks = true, 750 bool ForceSimpleCall = false); 751 752 /// \brief Check if the specified \a ScheduleKind is static non-chunked. 753 /// This kind of worksharing directive is emitted without outer loop. 754 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. 755 /// \param Chunked True if chunk is specified in the clause. 756 /// 757 virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, 758 bool Chunked) const; 759 760 /// \brief Check if the specified \a ScheduleKind is static non-chunked. 761 /// This kind of distribute directive is emitted without outer loop. 762 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. 763 /// \param Chunked True if chunk is specified in the clause. 764 /// 765 virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, 766 bool Chunked) const; 767 768 /// \brief Check if the specified \a ScheduleKind is dynamic. 769 /// This kind of worksharing directive is emitted without outer loop. 770 /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. 771 /// 772 virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; 773 774 /// struct with the values to be passed to the dispatch runtime function 775 struct DispatchRTInput { 776 /// Loop lower bound 777 llvm::Value *LB = nullptr; 778 /// Loop upper bound 779 llvm::Value *UB = nullptr; 780 /// Chunk size specified using 'schedule' clause (nullptr if chunk 781 /// was not specified) 782 llvm::Value *Chunk = nullptr; 783 DispatchRTInput() = default; 784 DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) 785 : LB(LB), UB(UB), Chunk(Chunk) {} 786 }; 787 788 /// Call the appropriate runtime routine to initialize it before start 789 /// of loop. 790 791 /// This is used for non static scheduled types and when the ordered 792 /// clause is present on the loop construct. 793 /// Depending on the loop schedule, it is necessary to call some runtime 794 /// routine before start of the OpenMP loop to get the loop upper / lower 795 /// bounds \a LB and \a UB and stride \a ST. 796 /// 797 /// \param CGF Reference to current CodeGenFunction. 798 /// \param Loc Clang source location. 799 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 800 /// \param IVSize Size of the iteration variable in bits. 801 /// \param IVSigned Sign of the iteration variable. 802 /// \param Ordered true if loop is ordered, false otherwise. 803 /// \param DispatchValues struct containing llvm values for lower bound, upper 804 /// bound, and chunk expression. 805 /// For the default (nullptr) value, the chunk 1 will be used. 806 /// 807 virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 808 const OpenMPScheduleTy &ScheduleKind, 809 unsigned IVSize, bool IVSigned, bool Ordered, 810 const DispatchRTInput &DispatchValues); 811 812 /// Struct with the values to be passed to the static runtime function 813 struct StaticRTInput { 814 /// Size of the iteration variable in bits. 815 unsigned IVSize = 0; 816 /// Sign of the iteration variable. 817 bool IVSigned = false; 818 /// true if loop is ordered, false otherwise. 819 bool Ordered = false; 820 /// Address of the output variable in which the flag of the last iteration 821 /// is returned. 822 Address IL = Address::invalid(); 823 /// Address of the output variable in which the lower iteration number is 824 /// returned. 825 Address LB = Address::invalid(); 826 /// Address of the output variable in which the upper iteration number is 827 /// returned. 828 Address UB = Address::invalid(); 829 /// Address of the output variable in which the stride value is returned 830 /// necessary to generated the static_chunked scheduled loop. 831 Address ST = Address::invalid(); 832 /// Value of the chunk for the static_chunked scheduled loop. For the 833 /// default (nullptr) value, the chunk 1 will be used. 834 llvm::Value *Chunk = nullptr; 835 StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, 836 Address LB, Address UB, Address ST, 837 llvm::Value *Chunk = nullptr) 838 : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), 839 UB(UB), ST(ST), Chunk(Chunk) {} 840 }; 841 /// \brief Call the appropriate runtime routine to initialize it before start 842 /// of loop. 843 /// 844 /// This is used only in case of static schedule, when the user did not 845 /// specify a ordered clause on the loop construct. 846 /// Depending on the loop schedule, it is necessary to call some runtime 847 /// routine before start of the OpenMP loop to get the loop upper / lower 848 /// bounds LB and UB and stride ST. 849 /// 850 /// \param CGF Reference to current CodeGenFunction. 851 /// \param Loc Clang source location. 852 /// \param DKind Kind of the directive. 853 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 854 /// \param Values Input arguments for the construct. 855 /// 856 virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 857 OpenMPDirectiveKind DKind, 858 const OpenMPScheduleTy &ScheduleKind, 859 const StaticRTInput &Values); 860 861 /// 862 /// \param CGF Reference to current CodeGenFunction. 863 /// \param Loc Clang source location. 864 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 865 /// \param Values Input arguments for the construct. 866 /// 867 virtual void emitDistributeStaticInit(CodeGenFunction &CGF, 868 SourceLocation Loc, 869 OpenMPDistScheduleClauseKind SchedKind, 870 const StaticRTInput &Values); 871 872 /// \brief Call the appropriate runtime routine to notify that we finished 873 /// iteration of the ordered loop with the dynamic scheduling. 874 /// 875 /// \param CGF Reference to current CodeGenFunction. 876 /// \param Loc Clang source location. 877 /// \param IVSize Size of the iteration variable in bits. 878 /// \param IVSigned Sign of the iteration variable. 879 /// 880 virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, 881 SourceLocation Loc, unsigned IVSize, 882 bool IVSigned); 883 884 /// \brief Call the appropriate runtime routine to notify that we finished 885 /// all the work with current loop. 886 /// 887 /// \param CGF Reference to current CodeGenFunction. 888 /// \param Loc Clang source location. 889 /// \param DKind Kind of the directive for which the static finish is emitted. 890 /// 891 virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 892 OpenMPDirectiveKind DKind); 893 894 /// Call __kmpc_dispatch_next( 895 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 896 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 897 /// kmp_int[32|64] *p_stride); 898 /// \param IVSize Size of the iteration variable in bits. 899 /// \param IVSigned Sign of the iteration variable. 900 /// \param IL Address of the output variable in which the flag of the 901 /// last iteration is returned. 902 /// \param LB Address of the output variable in which the lower iteration 903 /// number is returned. 904 /// \param UB Address of the output variable in which the upper iteration 905 /// number is returned. 906 /// \param ST Address of the output variable in which the stride value is 907 /// returned. 908 virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 909 unsigned IVSize, bool IVSigned, 910 Address IL, Address LB, 911 Address UB, Address ST); 912 913 /// \brief Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 914 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 915 /// clause. 916 /// \param NumThreads An integer value of threads. 917 virtual void emitNumThreadsClause(CodeGenFunction &CGF, 918 llvm::Value *NumThreads, 919 SourceLocation Loc); 920 921 /// \brief Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 922 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 923 virtual void emitProcBindClause(CodeGenFunction &CGF, 924 OpenMPProcBindClauseKind ProcBind, 925 SourceLocation Loc); 926 927 /// \brief Returns address of the threadprivate variable for the current 928 /// thread. 929 /// \param VD Threadprivate variable. 930 /// \param VDAddr Address of the global variable \a VD. 931 /// \param Loc Location of the reference to threadprivate var. 932 /// \return Address of the threadprivate variable for the current thread. 933 virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, 934 const VarDecl *VD, 935 Address VDAddr, 936 SourceLocation Loc); 937 938 /// \brief Emit a code for initialization of threadprivate variable. It emits 939 /// a call to runtime library which adds initial value to the newly created 940 /// threadprivate variable (if it is not constant) and registers destructor 941 /// for the variable (if any). 942 /// \param VD Threadprivate variable. 943 /// \param VDAddr Address of the global variable \a VD. 944 /// \param Loc Location of threadprivate declaration. 945 /// \param PerformInit true if initialization expression is not constant. 946 virtual llvm::Function * 947 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 948 SourceLocation Loc, bool PerformInit, 949 CodeGenFunction *CGF = nullptr); 950 951 /// Creates artificial threadprivate variable with name \p Name and type \p 952 /// VarType. 953 /// \param VarType Type of the artificial threadprivate variable. 954 /// \param Name Name of the artificial threadprivate variable. 955 virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 956 QualType VarType, 957 StringRef Name); 958 959 /// \brief Emit flush of the variables specified in 'omp flush' directive. 960 /// \param Vars List of variables to flush. 961 virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 962 SourceLocation Loc); 963 964 /// \brief Emit task region for the task directive. The task region is 965 /// emitted in several steps: 966 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 967 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 968 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 969 /// function: 970 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 971 /// TaskFunction(gtid, tt->part_id, tt->shareds); 972 /// return 0; 973 /// } 974 /// 2. Copy a list of shared variables to field shareds of the resulting 975 /// structure kmp_task_t returned by the previous call (if any). 976 /// 3. Copy a pointer to destructions function to field destructions of the 977 /// resulting structure kmp_task_t. 978 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 979 /// kmp_task_t *new_task), where new_task is a resulting structure from 980 /// previous items. 981 /// \param D Current task directive. 982 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 983 /// /*part_id*/, captured_struct */*__context*/); 984 /// \param SharedsTy A type which contains references the shared variables. 985 /// \param Shareds Context with the list of shared variables from the \p 986 /// TaskFunction. 987 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 988 /// otherwise. 989 /// \param Data Additional data for task generation like tiednsee, final 990 /// state, list of privates etc. 991 virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 992 const OMPExecutableDirective &D, 993 llvm::Value *TaskFunction, QualType SharedsTy, 994 Address Shareds, const Expr *IfCond, 995 const OMPTaskDataTy &Data); 996 997 /// Emit task region for the taskloop directive. The taskloop region is 998 /// emitted in several steps: 999 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1000 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1001 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1002 /// function: 1003 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1004 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1005 /// return 0; 1006 /// } 1007 /// 2. Copy a list of shared variables to field shareds of the resulting 1008 /// structure kmp_task_t returned by the previous call (if any). 1009 /// 3. Copy a pointer to destructions function to field destructions of the 1010 /// resulting structure kmp_task_t. 1011 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 1012 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 1013 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 1014 /// is a resulting structure from 1015 /// previous items. 1016 /// \param D Current task directive. 1017 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1018 /// /*part_id*/, captured_struct */*__context*/); 1019 /// \param SharedsTy A type which contains references the shared variables. 1020 /// \param Shareds Context with the list of shared variables from the \p 1021 /// TaskFunction. 1022 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1023 /// otherwise. 1024 /// \param Data Additional data for task generation like tiednsee, final 1025 /// state, list of privates etc. 1026 virtual void emitTaskLoopCall( 1027 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, 1028 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds, 1029 const Expr *IfCond, const OMPTaskDataTy &Data); 1030 1031 /// \brief Emit code for the directive that does not require outlining. 1032 /// 1033 /// \param InnermostKind Kind of innermost directive (for simple directives it 1034 /// is a directive itself, for combined - its innermost directive). 1035 /// \param CodeGen Code generation sequence for the \a D directive. 1036 /// \param HasCancel true if region has inner cancel directive, false 1037 /// otherwise. 1038 virtual void emitInlinedDirective(CodeGenFunction &CGF, 1039 OpenMPDirectiveKind InnermostKind, 1040 const RegionCodeGenTy &CodeGen, 1041 bool HasCancel = false); 1042 1043 /// Emits reduction function. 1044 /// \param ArgsType Array type containing pointers to reduction variables. 1045 /// \param Privates List of private copies for original reduction arguments. 1046 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1047 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1048 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1049 /// or 'operator binop(LHS, RHS)'. 1050 llvm::Value *emitReductionFunction(CodeGenModule &CGM, SourceLocation Loc, 1051 llvm::Type *ArgsType, 1052 ArrayRef<const Expr *> Privates, 1053 ArrayRef<const Expr *> LHSExprs, 1054 ArrayRef<const Expr *> RHSExprs, 1055 ArrayRef<const Expr *> ReductionOps); 1056 1057 /// Emits single reduction combiner 1058 void emitSingleReductionCombiner(CodeGenFunction &CGF, 1059 const Expr *ReductionOp, 1060 const Expr *PrivateRef, 1061 const DeclRefExpr *LHS, 1062 const DeclRefExpr *RHS); 1063 1064 struct ReductionOptionsTy { 1065 bool WithNowait; 1066 bool SimpleReduction; 1067 OpenMPDirectiveKind ReductionKind; 1068 }; 1069 /// \brief Emit a code for reduction clause. Next code should be emitted for 1070 /// reduction: 1071 /// \code 1072 /// 1073 /// static kmp_critical_name lock = { 0 }; 1074 /// 1075 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 1076 /// ... 1077 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 1078 /// ... 1079 /// } 1080 /// 1081 /// ... 1082 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 1083 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 1084 /// RedList, reduce_func, &<lock>)) { 1085 /// case 1: 1086 /// ... 1087 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 1088 /// ... 1089 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 1090 /// break; 1091 /// case 2: 1092 /// ... 1093 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 1094 /// ... 1095 /// break; 1096 /// default:; 1097 /// } 1098 /// \endcode 1099 /// 1100 /// \param Privates List of private copies for original reduction arguments. 1101 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1102 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1103 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1104 /// or 'operator binop(LHS, RHS)'. 1105 /// \param Options List of options for reduction codegen: 1106 /// WithNowait true if parent directive has also nowait clause, false 1107 /// otherwise. 1108 /// SimpleReduction Emit reduction operation only. Used for omp simd 1109 /// directive on the host. 1110 /// ReductionKind The kind of reduction to perform. 1111 virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 1112 ArrayRef<const Expr *> Privates, 1113 ArrayRef<const Expr *> LHSExprs, 1114 ArrayRef<const Expr *> RHSExprs, 1115 ArrayRef<const Expr *> ReductionOps, 1116 ReductionOptionsTy Options); 1117 1118 /// Emit a code for initialization of task reduction clause. Next code 1119 /// should be emitted for reduction: 1120 /// \code 1121 /// 1122 /// _task_red_item_t red_data[n]; 1123 /// ... 1124 /// red_data[i].shar = &origs[i]; 1125 /// red_data[i].size = sizeof(origs[i]); 1126 /// red_data[i].f_init = (void*)RedInit<i>; 1127 /// red_data[i].f_fini = (void*)RedDest<i>; 1128 /// red_data[i].f_comb = (void*)RedOp<i>; 1129 /// red_data[i].flags = <Flag_i>; 1130 /// ... 1131 /// void* tg1 = __kmpc_task_reduction_init(gtid, n, red_data); 1132 /// \endcode 1133 /// 1134 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 1135 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 1136 /// \param Data Additional data for task generation like tiedness, final 1137 /// state, list of privates, reductions etc. 1138 virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, 1139 SourceLocation Loc, 1140 ArrayRef<const Expr *> LHSExprs, 1141 ArrayRef<const Expr *> RHSExprs, 1142 const OMPTaskDataTy &Data); 1143 1144 /// Required to resolve existing problems in the runtime. Emits threadprivate 1145 /// variables to store the size of the VLAs/array sections for 1146 /// initializer/combiner/finalizer functions + emits threadprivate variable to 1147 /// store the pointer to the original reduction item for the custom 1148 /// initializer defined by declare reduction construct. 1149 /// \param RCG Allows to reuse an existing data for the reductions. 1150 /// \param N Reduction item for which fixups must be emitted. 1151 virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 1152 ReductionCodeGen &RCG, unsigned N); 1153 1154 /// Get the address of `void *` type of the privatue copy of the reduction 1155 /// item specified by the \p SharedLVal. 1156 /// \param ReductionsPtr Pointer to the reduction data returned by the 1157 /// emitTaskReductionInit function. 1158 /// \param SharedLVal Address of the original reduction item. 1159 virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 1160 llvm::Value *ReductionsPtr, 1161 LValue SharedLVal); 1162 1163 /// \brief Emit code for 'taskwait' directive. 1164 virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc); 1165 1166 /// \brief Emit code for 'cancellation point' construct. 1167 /// \param CancelRegion Region kind for which the cancellation point must be 1168 /// emitted. 1169 /// 1170 virtual void emitCancellationPointCall(CodeGenFunction &CGF, 1171 SourceLocation Loc, 1172 OpenMPDirectiveKind CancelRegion); 1173 1174 /// \brief Emit code for 'cancel' construct. 1175 /// \param IfCond Condition in the associated 'if' clause, if it was 1176 /// specified, nullptr otherwise. 1177 /// \param CancelRegion Region kind for which the cancel must be emitted. 1178 /// 1179 virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 1180 const Expr *IfCond, 1181 OpenMPDirectiveKind CancelRegion); 1182 1183 /// \brief Emit outilined function for 'target' directive. 1184 /// \param D Directive to emit. 1185 /// \param ParentName Name of the function that encloses the target region. 1186 /// \param OutlinedFn Outlined function value to be defined by this call. 1187 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 1188 /// \param IsOffloadEntry True if the outlined function is an offload entry. 1189 /// \param CodeGen Code generation sequence for the \a D directive. 1190 /// An outlined function may not be an entry if, e.g. the if clause always 1191 /// evaluates to false. 1192 virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 1193 StringRef ParentName, 1194 llvm::Function *&OutlinedFn, 1195 llvm::Constant *&OutlinedFnID, 1196 bool IsOffloadEntry, 1197 const RegionCodeGenTy &CodeGen); 1198 1199 /// \brief Emit the target offloading code associated with \a D. The emitted 1200 /// code attempts offloading the execution to the device, an the event of 1201 /// a failure it executes the host version outlined in \a OutlinedFn. 1202 /// \param D Directive to emit. 1203 /// \param OutlinedFn Host version of the code to be offloaded. 1204 /// \param OutlinedFnID ID of host version of the code to be offloaded. 1205 /// \param IfCond Expression evaluated in if clause associated with the target 1206 /// directive, or null if no if clause is used. 1207 /// \param Device Expression evaluated in device clause associated with the 1208 /// target directive, or null if no device clause is used. 1209 virtual void emitTargetCall(CodeGenFunction &CGF, 1210 const OMPExecutableDirective &D, 1211 llvm::Value *OutlinedFn, 1212 llvm::Value *OutlinedFnID, const Expr *IfCond, 1213 const Expr *Device); 1214 1215 /// \brief Emit the target regions enclosed in \a GD function definition or 1216 /// the function itself in case it is a valid device function. Returns true if 1217 /// \a GD was dealt with successfully. 1218 /// \param GD Function to scan. 1219 virtual bool emitTargetFunctions(GlobalDecl GD); 1220 1221 /// \brief Emit the global variable if it is a valid device global variable. 1222 /// Returns true if \a GD was dealt with successfully. 1223 /// \param GD Variable declaration to emit. 1224 virtual bool emitTargetGlobalVariable(GlobalDecl GD); 1225 1226 /// \brief Emit the global \a GD if it is meaningful for the target. Returns 1227 /// if it was emitted successfully. 1228 /// \param GD Global to scan. 1229 virtual bool emitTargetGlobal(GlobalDecl GD); 1230 1231 /// \brief Creates the offloading descriptor in the event any target region 1232 /// was emitted in the current module and return the function that registers 1233 /// it. 1234 virtual llvm::Function *emitRegistrationFunction(); 1235 1236 /// \brief Emits code for teams call of the \a OutlinedFn with 1237 /// variables captured in a record which address is stored in \a 1238 /// CapturedStruct. 1239 /// \param OutlinedFn Outlined function to be run by team masters. Type of 1240 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1241 /// \param CapturedVars A pointer to the record with the references to 1242 /// variables used in \a OutlinedFn function. 1243 /// 1244 virtual void emitTeamsCall(CodeGenFunction &CGF, 1245 const OMPExecutableDirective &D, 1246 SourceLocation Loc, llvm::Value *OutlinedFn, 1247 ArrayRef<llvm::Value *> CapturedVars); 1248 1249 /// \brief Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 1250 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 1251 /// for num_teams clause. 1252 /// \param NumTeams An integer expression of teams. 1253 /// \param ThreadLimit An integer expression of threads. 1254 virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 1255 const Expr *ThreadLimit, SourceLocation Loc); 1256 1257 /// Struct that keeps all the relevant information that should be kept 1258 /// throughout a 'target data' region. 1259 class TargetDataInfo { 1260 /// Set to true if device pointer information have to be obtained. 1261 bool RequiresDevicePointerInfo = false; 1262 1263 public: 1264 /// The array of base pointer passed to the runtime library. 1265 llvm::Value *BasePointersArray = nullptr; 1266 /// The array of section pointers passed to the runtime library. 1267 llvm::Value *PointersArray = nullptr; 1268 /// The array of sizes passed to the runtime library. 1269 llvm::Value *SizesArray = nullptr; 1270 /// The array of map types passed to the runtime library. 1271 llvm::Value *MapTypesArray = nullptr; 1272 /// The total number of pointers passed to the runtime library. 1273 unsigned NumberOfPtrs = 0u; 1274 /// Map between the a declaration of a capture and the corresponding base 1275 /// pointer address where the runtime returns the device pointers. 1276 llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; 1277 1278 explicit TargetDataInfo() {} 1279 explicit TargetDataInfo(bool RequiresDevicePointerInfo) 1280 : RequiresDevicePointerInfo(RequiresDevicePointerInfo) {} 1281 /// Clear information about the data arrays. 1282 void clearArrayInfo() { 1283 BasePointersArray = nullptr; 1284 PointersArray = nullptr; 1285 SizesArray = nullptr; 1286 MapTypesArray = nullptr; 1287 NumberOfPtrs = 0u; 1288 } 1289 /// Return true if the current target data information has valid arrays. 1290 bool isValid() { 1291 return BasePointersArray && PointersArray && SizesArray && 1292 MapTypesArray && NumberOfPtrs; 1293 } 1294 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } 1295 }; 1296 1297 /// \brief Emit the target data mapping code associated with \a D. 1298 /// \param D Directive to emit. 1299 /// \param IfCond Expression evaluated in if clause associated with the 1300 /// target directive, or null if no device clause is used. 1301 /// \param Device Expression evaluated in device clause associated with the 1302 /// target directive, or null if no device clause is used. 1303 /// \param Info A record used to store information that needs to be preserved 1304 /// until the region is closed. 1305 virtual void emitTargetDataCalls(CodeGenFunction &CGF, 1306 const OMPExecutableDirective &D, 1307 const Expr *IfCond, const Expr *Device, 1308 const RegionCodeGenTy &CodeGen, 1309 TargetDataInfo &Info); 1310 1311 /// \brief Emit the data mapping/movement code associated with the directive 1312 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 1313 /// \param D Directive to emit. 1314 /// \param IfCond Expression evaluated in if clause associated with the target 1315 /// directive, or null if no if clause is used. 1316 /// \param Device Expression evaluated in device clause associated with the 1317 /// target directive, or null if no device clause is used. 1318 virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 1319 const OMPExecutableDirective &D, 1320 const Expr *IfCond, 1321 const Expr *Device); 1322 1323 /// Marks function \a Fn with properly mangled versions of vector functions. 1324 /// \param FD Function marked as 'declare simd'. 1325 /// \param Fn LLVM function that must be marked with 'declare simd' 1326 /// attributes. 1327 virtual void emitDeclareSimdFunction(const FunctionDecl *FD, 1328 llvm::Function *Fn); 1329 1330 /// Emit initialization for doacross loop nesting support. 1331 /// \param D Loop-based construct used in doacross nesting construct. 1332 virtual void emitDoacrossInit(CodeGenFunction &CGF, 1333 const OMPLoopDirective &D); 1334 1335 /// Emit code for doacross ordered directive with 'depend' clause. 1336 /// \param C 'depend' clause with 'sink|source' dependency kind. 1337 virtual void emitDoacrossOrdered(CodeGenFunction &CGF, 1338 const OMPDependClause *C); 1339 1340 /// Translates the native parameter of outlined function if this is required 1341 /// for target. 1342 /// \param FD Field decl from captured record for the paramater. 1343 /// \param NativeParam Parameter itself. 1344 virtual const VarDecl *translateParameter(const FieldDecl *FD, 1345 const VarDecl *NativeParam) const { 1346 return NativeParam; 1347 } 1348 1349 /// Gets the address of the native argument basing on the address of the 1350 /// target-specific parameter. 1351 /// \param NativeParam Parameter itself. 1352 /// \param TargetParam Corresponding target-specific parameter. 1353 virtual Address getParameterAddress(CodeGenFunction &CGF, 1354 const VarDecl *NativeParam, 1355 const VarDecl *TargetParam) const; 1356 1357 /// Emits call of the outlined function with the provided arguments, 1358 /// translating these arguments to correct target-specific arguments. 1359 virtual void 1360 emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, 1361 llvm::Value *OutlinedFn, 1362 ArrayRef<llvm::Value *> Args = llvm::None) const; 1363 }; 1364 1365 /// Class supports emissionof SIMD-only code. 1366 class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { 1367 public: 1368 explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} 1369 ~CGOpenMPSIMDRuntime() override {} 1370 1371 /// \brief Emits outlined function for the specified OpenMP parallel directive 1372 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1373 /// kmp_int32 BoundID, struct context_vars*). 1374 /// \param D OpenMP directive. 1375 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1376 /// \param InnermostKind Kind of innermost directive (for simple directives it 1377 /// is a directive itself, for combined - its innermost directive). 1378 /// \param CodeGen Code generation sequence for the \a D directive. 1379 llvm::Value * 1380 emitParallelOutlinedFunction(const OMPExecutableDirective &D, 1381 const VarDecl *ThreadIDVar, 1382 OpenMPDirectiveKind InnermostKind, 1383 const RegionCodeGenTy &CodeGen) override; 1384 1385 /// \brief Emits outlined function for the specified OpenMP teams directive 1386 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1387 /// kmp_int32 BoundID, struct context_vars*). 1388 /// \param D OpenMP directive. 1389 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1390 /// \param InnermostKind Kind of innermost directive (for simple directives it 1391 /// is a directive itself, for combined - its innermost directive). 1392 /// \param CodeGen Code generation sequence for the \a D directive. 1393 llvm::Value * 1394 emitTeamsOutlinedFunction(const OMPExecutableDirective &D, 1395 const VarDecl *ThreadIDVar, 1396 OpenMPDirectiveKind InnermostKind, 1397 const RegionCodeGenTy &CodeGen) override; 1398 1399 /// \brief Emits outlined function for the OpenMP task directive \a D. This 1400 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 1401 /// TaskT). 1402 /// \param D OpenMP directive. 1403 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1404 /// \param PartIDVar Variable for partition id in the current OpenMP untied 1405 /// task region. 1406 /// \param TaskTVar Variable for task_t argument. 1407 /// \param InnermostKind Kind of innermost directive (for simple directives it 1408 /// is a directive itself, for combined - its innermost directive). 1409 /// \param CodeGen Code generation sequence for the \a D directive. 1410 /// \param Tied true if task is generated for tied task, false otherwise. 1411 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 1412 /// tasks. 1413 /// 1414 llvm::Value *emitTaskOutlinedFunction( 1415 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1416 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 1417 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1418 bool Tied, unsigned &NumberOfParts) override; 1419 1420 /// \brief Emits code for parallel or serial call of the \a OutlinedFn with 1421 /// variables captured in a record which address is stored in \a 1422 /// CapturedStruct. 1423 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 1424 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1425 /// \param CapturedVars A pointer to the record with the references to 1426 /// variables used in \a OutlinedFn function. 1427 /// \param IfCond Condition in the associated 'if' clause, if it was 1428 /// specified, nullptr otherwise. 1429 /// 1430 void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 1431 llvm::Value *OutlinedFn, 1432 ArrayRef<llvm::Value *> CapturedVars, 1433 const Expr *IfCond) override; 1434 1435 /// \brief Emits a critical region. 1436 /// \param CriticalName Name of the critical region. 1437 /// \param CriticalOpGen Generator for the statement associated with the given 1438 /// critical region. 1439 /// \param Hint Value of the 'hint' clause (optional). 1440 void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 1441 const RegionCodeGenTy &CriticalOpGen, 1442 SourceLocation Loc, 1443 const Expr *Hint = nullptr) override; 1444 1445 /// \brief Emits a master region. 1446 /// \param MasterOpGen Generator for the statement associated with the given 1447 /// master region. 1448 void emitMasterRegion(CodeGenFunction &CGF, 1449 const RegionCodeGenTy &MasterOpGen, 1450 SourceLocation Loc) override; 1451 1452 /// \brief Emits code for a taskyield directive. 1453 void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; 1454 1455 /// \brief Emit a taskgroup region. 1456 /// \param TaskgroupOpGen Generator for the statement associated with the 1457 /// given taskgroup region. 1458 void emitTaskgroupRegion(CodeGenFunction &CGF, 1459 const RegionCodeGenTy &TaskgroupOpGen, 1460 SourceLocation Loc) override; 1461 1462 /// \brief Emits a single region. 1463 /// \param SingleOpGen Generator for the statement associated with the given 1464 /// single region. 1465 void emitSingleRegion(CodeGenFunction &CGF, 1466 const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, 1467 ArrayRef<const Expr *> CopyprivateVars, 1468 ArrayRef<const Expr *> DestExprs, 1469 ArrayRef<const Expr *> SrcExprs, 1470 ArrayRef<const Expr *> AssignmentOps) override; 1471 1472 /// \brief Emit an ordered region. 1473 /// \param OrderedOpGen Generator for the statement associated with the given 1474 /// ordered region. 1475 void emitOrderedRegion(CodeGenFunction &CGF, 1476 const RegionCodeGenTy &OrderedOpGen, 1477 SourceLocation Loc, bool IsThreads) override; 1478 1479 /// \brief Emit an implicit/explicit barrier for OpenMP threads. 1480 /// \param Kind Directive for which this implicit barrier call must be 1481 /// generated. Must be OMPD_barrier for explicit barrier generation. 1482 /// \param EmitChecks true if need to emit checks for cancellation barriers. 1483 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 1484 /// runtime class decides which one to emit (simple or with cancellation 1485 /// checks). 1486 /// 1487 void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 1488 OpenMPDirectiveKind Kind, bool EmitChecks = true, 1489 bool ForceSimpleCall = false) override; 1490 1491 /// This is used for non static scheduled types and when the ordered 1492 /// clause is present on the loop construct. 1493 /// Depending on the loop schedule, it is necessary to call some runtime 1494 /// routine before start of the OpenMP loop to get the loop upper / lower 1495 /// bounds \a LB and \a UB and stride \a ST. 1496 /// 1497 /// \param CGF Reference to current CodeGenFunction. 1498 /// \param Loc Clang source location. 1499 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1500 /// \param IVSize Size of the iteration variable in bits. 1501 /// \param IVSigned Sign of the iteration variable. 1502 /// \param Ordered true if loop is ordered, false otherwise. 1503 /// \param DispatchValues struct containing llvm values for lower bound, upper 1504 /// bound, and chunk expression. 1505 /// For the default (nullptr) value, the chunk 1 will be used. 1506 /// 1507 void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 1508 const OpenMPScheduleTy &ScheduleKind, 1509 unsigned IVSize, bool IVSigned, bool Ordered, 1510 const DispatchRTInput &DispatchValues) override; 1511 1512 /// \brief Call the appropriate runtime routine to initialize it before start 1513 /// of loop. 1514 /// 1515 /// This is used only in case of static schedule, when the user did not 1516 /// specify a ordered clause on the loop construct. 1517 /// Depending on the loop schedule, it is necessary to call some runtime 1518 /// routine before start of the OpenMP loop to get the loop upper / lower 1519 /// bounds LB and UB and stride ST. 1520 /// 1521 /// \param CGF Reference to current CodeGenFunction. 1522 /// \param Loc Clang source location. 1523 /// \param DKind Kind of the directive. 1524 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1525 /// \param Values Input arguments for the construct. 1526 /// 1527 void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1528 OpenMPDirectiveKind DKind, 1529 const OpenMPScheduleTy &ScheduleKind, 1530 const StaticRTInput &Values) override; 1531 1532 /// 1533 /// \param CGF Reference to current CodeGenFunction. 1534 /// \param Loc Clang source location. 1535 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 1536 /// \param Values Input arguments for the construct. 1537 /// 1538 void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1539 OpenMPDistScheduleClauseKind SchedKind, 1540 const StaticRTInput &Values) override; 1541 1542 /// \brief Call the appropriate runtime routine to notify that we finished 1543 /// iteration of the ordered loop with the dynamic scheduling. 1544 /// 1545 /// \param CGF Reference to current CodeGenFunction. 1546 /// \param Loc Clang source location. 1547 /// \param IVSize Size of the iteration variable in bits. 1548 /// \param IVSigned Sign of the iteration variable. 1549 /// 1550 void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, 1551 unsigned IVSize, bool IVSigned) override; 1552 1553 /// \brief Call the appropriate runtime routine to notify that we finished 1554 /// all the work with current loop. 1555 /// 1556 /// \param CGF Reference to current CodeGenFunction. 1557 /// \param Loc Clang source location. 1558 /// \param DKind Kind of the directive for which the static finish is emitted. 1559 /// 1560 void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 1561 OpenMPDirectiveKind DKind) override; 1562 1563 /// Call __kmpc_dispatch_next( 1564 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 1565 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 1566 /// kmp_int[32|64] *p_stride); 1567 /// \param IVSize Size of the iteration variable in bits. 1568 /// \param IVSigned Sign of the iteration variable. 1569 /// \param IL Address of the output variable in which the flag of the 1570 /// last iteration is returned. 1571 /// \param LB Address of the output variable in which the lower iteration 1572 /// number is returned. 1573 /// \param UB Address of the output variable in which the upper iteration 1574 /// number is returned. 1575 /// \param ST Address of the output variable in which the stride value is 1576 /// returned. 1577 llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 1578 unsigned IVSize, bool IVSigned, Address IL, 1579 Address LB, Address UB, Address ST) override; 1580 1581 /// \brief Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 1582 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 1583 /// clause. 1584 /// \param NumThreads An integer value of threads. 1585 void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, 1586 SourceLocation Loc) override; 1587 1588 /// \brief Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 1589 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 1590 void emitProcBindClause(CodeGenFunction &CGF, 1591 OpenMPProcBindClauseKind ProcBind, 1592 SourceLocation Loc) override; 1593 1594 /// \brief Returns address of the threadprivate variable for the current 1595 /// thread. 1596 /// \param VD Threadprivate variable. 1597 /// \param VDAddr Address of the global variable \a VD. 1598 /// \param Loc Location of the reference to threadprivate var. 1599 /// \return Address of the threadprivate variable for the current thread. 1600 Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, 1601 Address VDAddr, SourceLocation Loc) override; 1602 1603 /// \brief Emit a code for initialization of threadprivate variable. It emits 1604 /// a call to runtime library which adds initial value to the newly created 1605 /// threadprivate variable (if it is not constant) and registers destructor 1606 /// for the variable (if any). 1607 /// \param VD Threadprivate variable. 1608 /// \param VDAddr Address of the global variable \a VD. 1609 /// \param Loc Location of threadprivate declaration. 1610 /// \param PerformInit true if initialization expression is not constant. 1611 llvm::Function * 1612 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 1613 SourceLocation Loc, bool PerformInit, 1614 CodeGenFunction *CGF = nullptr) override; 1615 1616 /// Creates artificial threadprivate variable with name \p Name and type \p 1617 /// VarType. 1618 /// \param VarType Type of the artificial threadprivate variable. 1619 /// \param Name Name of the artificial threadprivate variable. 1620 Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 1621 QualType VarType, 1622 StringRef Name) override; 1623 1624 /// \brief Emit flush of the variables specified in 'omp flush' directive. 1625 /// \param Vars List of variables to flush. 1626 void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 1627 SourceLocation Loc) override; 1628 1629 /// \brief Emit task region for the task directive. The task region is 1630 /// emitted in several steps: 1631 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1632 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1633 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1634 /// function: 1635 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1636 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1637 /// return 0; 1638 /// } 1639 /// 2. Copy a list of shared variables to field shareds of the resulting 1640 /// structure kmp_task_t returned by the previous call (if any). 1641 /// 3. Copy a pointer to destructions function to field destructions of the 1642 /// resulting structure kmp_task_t. 1643 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 1644 /// kmp_task_t *new_task), where new_task is a resulting structure from 1645 /// previous items. 1646 /// \param D Current task directive. 1647 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1648 /// /*part_id*/, captured_struct */*__context*/); 1649 /// \param SharedsTy A type which contains references the shared variables. 1650 /// \param Shareds Context with the list of shared variables from the \p 1651 /// TaskFunction. 1652 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1653 /// otherwise. 1654 /// \param Data Additional data for task generation like tiednsee, final 1655 /// state, list of privates etc. 1656 void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 1657 const OMPExecutableDirective &D, llvm::Value *TaskFunction, 1658 QualType SharedsTy, Address Shareds, const Expr *IfCond, 1659 const OMPTaskDataTy &Data) override; 1660 1661 /// Emit task region for the taskloop directive. The taskloop region is 1662 /// emitted in several steps: 1663 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1664 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1665 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1666 /// function: 1667 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1668 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1669 /// return 0; 1670 /// } 1671 /// 2. Copy a list of shared variables to field shareds of the resulting 1672 /// structure kmp_task_t returned by the previous call (if any). 1673 /// 3. Copy a pointer to destructions function to field destructions of the 1674 /// resulting structure kmp_task_t. 1675 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 1676 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 1677 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 1678 /// is a resulting structure from 1679 /// previous items. 1680 /// \param D Current task directive. 1681 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1682 /// /*part_id*/, captured_struct */*__context*/); 1683 /// \param SharedsTy A type which contains references the shared variables. 1684 /// \param Shareds Context with the list of shared variables from the \p 1685 /// TaskFunction. 1686 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1687 /// otherwise. 1688 /// \param Data Additional data for task generation like tiednsee, final 1689 /// state, list of privates etc. 1690 void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 1691 const OMPLoopDirective &D, llvm::Value *TaskFunction, 1692 QualType SharedsTy, Address Shareds, const Expr *IfCond, 1693 const OMPTaskDataTy &Data) override; 1694 1695 /// \brief Emit a code for reduction clause. Next code should be emitted for 1696 /// reduction: 1697 /// \code 1698 /// 1699 /// static kmp_critical_name lock = { 0 }; 1700 /// 1701 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 1702 /// ... 1703 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 1704 /// ... 1705 /// } 1706 /// 1707 /// ... 1708 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 1709 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 1710 /// RedList, reduce_func, &<lock>)) { 1711 /// case 1: 1712 /// ... 1713 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 1714 /// ... 1715 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 1716 /// break; 1717 /// case 2: 1718 /// ... 1719 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 1720 /// ... 1721 /// break; 1722 /// default:; 1723 /// } 1724 /// \endcode 1725 /// 1726 /// \param Privates List of private copies for original reduction arguments. 1727 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1728 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1729 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1730 /// or 'operator binop(LHS, RHS)'. 1731 /// \param Options List of options for reduction codegen: 1732 /// WithNowait true if parent directive has also nowait clause, false 1733 /// otherwise. 1734 /// SimpleReduction Emit reduction operation only. Used for omp simd 1735 /// directive on the host. 1736 /// ReductionKind The kind of reduction to perform. 1737 void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 1738 ArrayRef<const Expr *> Privates, 1739 ArrayRef<const Expr *> LHSExprs, 1740 ArrayRef<const Expr *> RHSExprs, 1741 ArrayRef<const Expr *> ReductionOps, 1742 ReductionOptionsTy Options) override; 1743 1744 /// Emit a code for initialization of task reduction clause. Next code 1745 /// should be emitted for reduction: 1746 /// \code 1747 /// 1748 /// _task_red_item_t red_data[n]; 1749 /// ... 1750 /// red_data[i].shar = &origs[i]; 1751 /// red_data[i].size = sizeof(origs[i]); 1752 /// red_data[i].f_init = (void*)RedInit<i>; 1753 /// red_data[i].f_fini = (void*)RedDest<i>; 1754 /// red_data[i].f_comb = (void*)RedOp<i>; 1755 /// red_data[i].flags = <Flag_i>; 1756 /// ... 1757 /// void* tg1 = __kmpc_task_reduction_init(gtid, n, red_data); 1758 /// \endcode 1759 /// 1760 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 1761 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 1762 /// \param Data Additional data for task generation like tiedness, final 1763 /// state, list of privates, reductions etc. 1764 llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, 1765 ArrayRef<const Expr *> LHSExprs, 1766 ArrayRef<const Expr *> RHSExprs, 1767 const OMPTaskDataTy &Data) override; 1768 1769 /// Required to resolve existing problems in the runtime. Emits threadprivate 1770 /// variables to store the size of the VLAs/array sections for 1771 /// initializer/combiner/finalizer functions + emits threadprivate variable to 1772 /// store the pointer to the original reduction item for the custom 1773 /// initializer defined by declare reduction construct. 1774 /// \param RCG Allows to reuse an existing data for the reductions. 1775 /// \param N Reduction item for which fixups must be emitted. 1776 void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 1777 ReductionCodeGen &RCG, unsigned N) override; 1778 1779 /// Get the address of `void *` type of the privatue copy of the reduction 1780 /// item specified by the \p SharedLVal. 1781 /// \param ReductionsPtr Pointer to the reduction data returned by the 1782 /// emitTaskReductionInit function. 1783 /// \param SharedLVal Address of the original reduction item. 1784 Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 1785 llvm::Value *ReductionsPtr, 1786 LValue SharedLVal) override; 1787 1788 /// \brief Emit code for 'taskwait' directive. 1789 void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override; 1790 1791 /// \brief Emit code for 'cancellation point' construct. 1792 /// \param CancelRegion Region kind for which the cancellation point must be 1793 /// emitted. 1794 /// 1795 void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, 1796 OpenMPDirectiveKind CancelRegion) override; 1797 1798 /// \brief Emit code for 'cancel' construct. 1799 /// \param IfCond Condition in the associated 'if' clause, if it was 1800 /// specified, nullptr otherwise. 1801 /// \param CancelRegion Region kind for which the cancel must be emitted. 1802 /// 1803 void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 1804 const Expr *IfCond, 1805 OpenMPDirectiveKind CancelRegion) override; 1806 1807 /// \brief Emit outilined function for 'target' directive. 1808 /// \param D Directive to emit. 1809 /// \param ParentName Name of the function that encloses the target region. 1810 /// \param OutlinedFn Outlined function value to be defined by this call. 1811 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 1812 /// \param IsOffloadEntry True if the outlined function is an offload entry. 1813 /// \param CodeGen Code generation sequence for the \a D directive. 1814 /// An outlined function may not be an entry if, e.g. the if clause always 1815 /// evaluates to false. 1816 void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 1817 StringRef ParentName, 1818 llvm::Function *&OutlinedFn, 1819 llvm::Constant *&OutlinedFnID, 1820 bool IsOffloadEntry, 1821 const RegionCodeGenTy &CodeGen) override; 1822 1823 /// \brief Emit the target offloading code associated with \a D. The emitted 1824 /// code attempts offloading the execution to the device, an the event of 1825 /// a failure it executes the host version outlined in \a OutlinedFn. 1826 /// \param D Directive to emit. 1827 /// \param OutlinedFn Host version of the code to be offloaded. 1828 /// \param OutlinedFnID ID of host version of the code to be offloaded. 1829 /// \param IfCond Expression evaluated in if clause associated with the target 1830 /// directive, or null if no if clause is used. 1831 /// \param Device Expression evaluated in device clause associated with the 1832 /// target directive, or null if no device clause is used. 1833 void emitTargetCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, 1834 llvm::Value *OutlinedFn, llvm::Value *OutlinedFnID, 1835 const Expr *IfCond, const Expr *Device) override; 1836 1837 /// \brief Emit the target regions enclosed in \a GD function definition or 1838 /// the function itself in case it is a valid device function. Returns true if 1839 /// \a GD was dealt with successfully. 1840 /// \param GD Function to scan. 1841 bool emitTargetFunctions(GlobalDecl GD) override; 1842 1843 /// \brief Emit the global variable if it is a valid device global variable. 1844 /// Returns true if \a GD was dealt with successfully. 1845 /// \param GD Variable declaration to emit. 1846 bool emitTargetGlobalVariable(GlobalDecl GD) override; 1847 1848 /// \brief Emit the global \a GD if it is meaningful for the target. Returns 1849 /// if it was emitted successfully. 1850 /// \param GD Global to scan. 1851 bool emitTargetGlobal(GlobalDecl GD) override; 1852 1853 /// \brief Creates the offloading descriptor in the event any target region 1854 /// was emitted in the current module and return the function that registers 1855 /// it. 1856 llvm::Function *emitRegistrationFunction() override; 1857 1858 /// \brief Emits code for teams call of the \a OutlinedFn with 1859 /// variables captured in a record which address is stored in \a 1860 /// CapturedStruct. 1861 /// \param OutlinedFn Outlined function to be run by team masters. Type of 1862 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1863 /// \param CapturedVars A pointer to the record with the references to 1864 /// variables used in \a OutlinedFn function. 1865 /// 1866 void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, 1867 SourceLocation Loc, llvm::Value *OutlinedFn, 1868 ArrayRef<llvm::Value *> CapturedVars) override; 1869 1870 /// \brief Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 1871 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 1872 /// for num_teams clause. 1873 /// \param NumTeams An integer expression of teams. 1874 /// \param ThreadLimit An integer expression of threads. 1875 void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 1876 const Expr *ThreadLimit, SourceLocation Loc) override; 1877 1878 /// \brief Emit the target data mapping code associated with \a D. 1879 /// \param D Directive to emit. 1880 /// \param IfCond Expression evaluated in if clause associated with the 1881 /// target directive, or null if no device clause is used. 1882 /// \param Device Expression evaluated in device clause associated with the 1883 /// target directive, or null if no device clause is used. 1884 /// \param Info A record used to store information that needs to be preserved 1885 /// until the region is closed. 1886 void emitTargetDataCalls(CodeGenFunction &CGF, 1887 const OMPExecutableDirective &D, const Expr *IfCond, 1888 const Expr *Device, const RegionCodeGenTy &CodeGen, 1889 TargetDataInfo &Info) override; 1890 1891 /// \brief Emit the data mapping/movement code associated with the directive 1892 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 1893 /// \param D Directive to emit. 1894 /// \param IfCond Expression evaluated in if clause associated with the target 1895 /// directive, or null if no if clause is used. 1896 /// \param Device Expression evaluated in device clause associated with the 1897 /// target directive, or null if no device clause is used. 1898 void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 1899 const OMPExecutableDirective &D, 1900 const Expr *IfCond, 1901 const Expr *Device) override; 1902 1903 /// Emit initialization for doacross loop nesting support. 1904 /// \param D Loop-based construct used in doacross nesting construct. 1905 void emitDoacrossInit(CodeGenFunction &CGF, 1906 const OMPLoopDirective &D) override; 1907 1908 /// Emit code for doacross ordered directive with 'depend' clause. 1909 /// \param C 'depend' clause with 'sink|source' dependency kind. 1910 void emitDoacrossOrdered(CodeGenFunction &CGF, 1911 const OMPDependClause *C) override; 1912 1913 /// Translates the native parameter of outlined function if this is required 1914 /// for target. 1915 /// \param FD Field decl from captured record for the paramater. 1916 /// \param NativeParam Parameter itself. 1917 const VarDecl *translateParameter(const FieldDecl *FD, 1918 const VarDecl *NativeParam) const override; 1919 1920 /// Gets the address of the native argument basing on the address of the 1921 /// target-specific parameter. 1922 /// \param NativeParam Parameter itself. 1923 /// \param TargetParam Corresponding target-specific parameter. 1924 Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, 1925 const VarDecl *TargetParam) const override; 1926 }; 1927 1928 } // namespace CodeGen 1929 } // namespace clang 1930 1931 #endif 1932