1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides a class for OpenMP runtime code generation.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_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"
40 class OMPDependClause;
41 class OMPExecutableDirective;
42 class OMPLoopDirective;
44 class OMPDeclareReductionDecl;
49 class CodeGenFunction;
52 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
54 class PrePostActionTy {
56 explicit PrePostActionTy() {}
57 virtual void Enter(CodeGenFunction &CGF) {}
58 virtual void Exit(CodeGenFunction &CGF) {}
59 virtual ~PrePostActionTy() {}
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 {
66 typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &);
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);
78 template <typename Callable>
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;
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<std::pair<OpenMPDependClauseKind, const Expr *>, 4> Dependences;
100 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
101 llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule;
102 llvm::PointerIntPair<llvm::Value *, 1, bool> Priority;
103 unsigned NumberOfParts = 0;
105 bool Nogroup = false;
108 class CGOpenMPRuntime {
112 /// \brief Creates offloading entry for the provided entry ID \a ID,
113 /// address \a Addr, size \a Size, and flags \a Flags.
114 virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr,
115 uint64_t Size, int32_t Flags = 0);
117 /// \brief Helper to emit outlined function for 'target' directive.
118 /// \param D Directive to emit.
119 /// \param ParentName Name of the function that encloses the target region.
120 /// \param OutlinedFn Outlined function value to be defined by this call.
121 /// \param OutlinedFnID Outlined function ID value to be defined by this call.
122 /// \param IsOffloadEntry True if the outlined function is an offload entry.
123 /// \param CodeGen Lambda codegen specific to an accelerator device.
124 /// An oulined function may not be an entry if, e.g. the if clause always
125 /// evaluates to false.
126 virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D,
127 StringRef ParentName,
128 llvm::Function *&OutlinedFn,
129 llvm::Constant *&OutlinedFnID,
131 const RegionCodeGenTy &CodeGen);
134 /// \brief Default const ident_t object used for initialization of all other
136 llvm::Constant *DefaultOpenMPPSource = nullptr;
137 /// \brief Map of flags and corresponding default locations.
138 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDefaultLocMapTy;
139 OpenMPDefaultLocMapTy OpenMPDefaultLocMap;
140 Address getOrCreateDefaultLocation(unsigned Flags);
142 llvm::StructType *IdentTy = nullptr;
143 /// \brief Map for SourceLocation and OpenMP runtime library debug locations.
144 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy;
145 OpenMPDebugLocMapTy OpenMPDebugLocMap;
146 /// \brief The type for a microtask which gets passed to __kmpc_fork_call().
147 /// Original representation is:
148 /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);
149 llvm::FunctionType *Kmpc_MicroTy = nullptr;
150 /// \brief Stores debug location and ThreadID for the function.
151 struct DebugLocThreadIdTy {
152 llvm::Value *DebugLoc;
153 llvm::Value *ThreadID;
155 /// \brief Map of local debug location, ThreadId and functions.
156 typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy>
157 OpenMPLocThreadIDMapTy;
158 OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap;
159 /// Map of UDRs and corresponding combiner/initializer.
160 typedef llvm::DenseMap<const OMPDeclareReductionDecl *,
161 std::pair<llvm::Function *, llvm::Function *>>
164 /// Map of functions and locally defined UDRs.
165 typedef llvm::DenseMap<llvm::Function *,
166 SmallVector<const OMPDeclareReductionDecl *, 4>>
168 FunctionUDRMapTy FunctionUDRMap;
169 IdentifierInfo *In = nullptr;
170 IdentifierInfo *Out = nullptr;
171 IdentifierInfo *Priv = nullptr;
172 IdentifierInfo *Orig = nullptr;
173 /// \brief Type kmp_critical_name, originally defined as typedef kmp_int32
174 /// kmp_critical_name[8];
175 llvm::ArrayType *KmpCriticalNameTy;
176 /// \brief An ordered map of auto-generated variables to their unique names.
177 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
178 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
179 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
181 llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator>
183 /// \brief Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *);
184 llvm::Type *KmpRoutineEntryPtrTy = nullptr;
185 QualType KmpRoutineEntryPtrQTy;
186 /// \brief Type typedef struct kmp_task {
187 /// void * shareds; /**< pointer to block of pointers to
189 /// kmp_routine_entry_t routine; /**< pointer to routine to call for
190 /// executing task */
191 /// kmp_int32 part_id; /**< part id for the task */
192 /// kmp_routine_entry_t destructors; /* pointer to function to invoke
193 /// deconstructors of firstprivate C++ objects */
195 QualType KmpTaskTQTy;
196 /// \brief Type typedef struct kmp_depend_info {
197 /// kmp_intptr_t base_addr;
203 /// } kmp_depend_info_t;
204 QualType KmpDependInfoTy;
205 /// struct kmp_dim { // loop bounds info casted to kmp_int64
206 /// kmp_int64 lo; // lower
207 /// kmp_int64 up; // upper
208 /// kmp_int64 st; // stride
211 /// \brief Type struct __tgt_offload_entry{
212 /// void *addr; // Pointer to the offload entry info.
213 /// // (function or global)
214 /// char *name; // Name of the function or global.
215 /// size_t size; // Size of the entry info (0 if it a function).
217 QualType TgtOffloadEntryQTy;
218 /// struct __tgt_device_image{
219 /// void *ImageStart; // Pointer to the target code start.
220 /// void *ImageEnd; // Pointer to the target code end.
221 /// // We also add the host entries to the device image, as it may be useful
222 /// // for the target runtime to have access to that information.
223 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all
225 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the
226 /// // entries (non inclusive).
228 QualType TgtDeviceImageQTy;
229 /// struct __tgt_bin_desc{
230 /// int32_t NumDevices; // Number of devices supported.
231 /// __tgt_device_image *DeviceImages; // Arrays of device images
232 /// // (one per device).
233 /// __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
235 /// __tgt_offload_entry *EntriesEnd; // End of the table with all the
236 /// // entries (non inclusive).
238 QualType TgtBinaryDescriptorQTy;
239 /// \brief Entity that registers the offloading constants that were emitted so
241 class OffloadEntriesInfoManagerTy {
244 /// \brief Number of entries registered so far.
245 unsigned OffloadingEntriesNum;
248 /// Base class of the entries info.
249 class OffloadEntryInfo {
251 /// Kind of a given entry. Currently, only target regions are
253 enum OffloadingEntryInfoKinds : unsigned {
254 // Entry is a target region.
255 OFFLOAD_ENTRY_INFO_TARGET_REGION = 0,
256 // Invalid entry info.
257 OFFLOAD_ENTRY_INFO_INVALID = ~0u
261 : Flags(0), Order(~0u), Kind(OFFLOAD_ENTRY_INFO_INVALID) {}
262 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
264 : Flags(Flags), Order(Order), Kind(Kind) {}
266 bool isValid() const { return Order != ~0u; }
267 unsigned getOrder() const { return Order; }
268 OffloadingEntryInfoKinds getKind() const { return Kind; }
269 int32_t getFlags() const { return Flags; }
270 void setFlags(int32_t NewFlags) { Flags = NewFlags; }
271 static bool classof(const OffloadEntryInfo *Info) { return true; }
274 /// Flags associated with the device global.
277 /// Order this entry was emitted.
280 OffloadingEntryInfoKinds Kind;
283 /// \brief Return true if a there are no entries defined.
285 /// \brief Return number of entries defined so far.
286 unsigned size() const { return OffloadingEntriesNum; }
287 OffloadEntriesInfoManagerTy(CodeGenModule &CGM)
288 : CGM(CGM), OffloadingEntriesNum(0) {}
291 /// Target region entries related.
293 /// \brief Target region entries info.
294 class OffloadEntryInfoTargetRegion : public OffloadEntryInfo {
295 // \brief Address of the entity that has to be mapped for offloading.
296 llvm::Constant *Addr;
297 // \brief Address that can be used as the ID of the entry.
301 OffloadEntryInfoTargetRegion()
302 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, ~0u,
304 Addr(nullptr), ID(nullptr) {}
305 explicit OffloadEntryInfoTargetRegion(unsigned Order,
306 llvm::Constant *Addr,
307 llvm::Constant *ID, int32_t Flags)
308 : OffloadEntryInfo(OFFLOAD_ENTRY_INFO_TARGET_REGION, Order, Flags),
309 Addr(Addr), ID(ID) {}
311 llvm::Constant *getAddress() const { return Addr; }
312 llvm::Constant *getID() const { return ID; }
313 void setAddress(llvm::Constant *V) {
314 assert(!Addr && "Address as been set before!");
317 void setID(llvm::Constant *V) {
318 assert(!ID && "ID as been set before!");
321 static bool classof(const OffloadEntryInfo *Info) {
322 return Info->getKind() == OFFLOAD_ENTRY_INFO_TARGET_REGION;
325 /// \brief Initialize target region entry.
326 void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
327 StringRef ParentName, unsigned LineNum,
329 /// \brief Register target region entry.
330 void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
331 StringRef ParentName, unsigned LineNum,
332 llvm::Constant *Addr, llvm::Constant *ID,
334 /// \brief Return true if a target region entry with the provided
335 /// information exists.
336 bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
337 StringRef ParentName, unsigned LineNum) const;
338 /// brief Applies action \a Action on all registered entries.
339 typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned,
340 OffloadEntryInfoTargetRegion &)>
341 OffloadTargetRegionEntryInfoActTy;
342 void actOnTargetRegionEntriesInfo(
343 const OffloadTargetRegionEntryInfoActTy &Action);
346 // Storage for target region entries kind. The storage is to be indexed by
347 // file ID, device ID, parent function name and line number.
348 typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion>
349 OffloadEntriesTargetRegionPerLine;
350 typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine>
351 OffloadEntriesTargetRegionPerParentName;
352 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName>
353 OffloadEntriesTargetRegionPerFile;
354 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile>
355 OffloadEntriesTargetRegionPerDevice;
356 typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy;
357 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
359 OffloadEntriesInfoManagerTy OffloadEntriesInfoManager;
361 /// \brief Creates and registers offloading binary descriptor for the current
362 /// compilation unit. The function that does the registration is returned.
363 llvm::Function *createOffloadingBinaryDescriptorRegistration();
365 /// \brief Creates all the offload entries in the current compilation unit
366 /// along with the associated metadata.
367 void createOffloadEntriesAndInfoMetadata();
369 /// \brief Loads all the offload entries information from the host IR
371 void loadOffloadInfoMetadata();
373 /// \brief Returns __tgt_offload_entry type.
374 QualType getTgtOffloadEntryQTy();
376 /// \brief Returns __tgt_device_image type.
377 QualType getTgtDeviceImageQTy();
379 /// \brief Returns __tgt_bin_desc type.
380 QualType getTgtBinaryDescriptorQTy();
382 /// \brief Start scanning from statement \a S and and emit all target regions
383 /// found along the way.
384 /// \param S Starting statement.
385 /// \param ParentName Name of the function declaration that is being scanned.
386 void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);
388 /// \brief Build type kmp_routine_entry_t (if not built yet).
389 void emitKmpRoutineEntryT(QualType KmpInt32Ty);
391 /// \brief Emits object of ident_t type with info for source location.
392 /// \param Flags Flags for OpenMP location.
394 llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
397 /// \brief Returns pointer to ident_t type.
398 llvm::Type *getIdentTyPointerTy();
400 /// \brief Returns pointer to kmpc_micro type.
401 llvm::Type *getKmpc_MicroPointerTy();
403 /// \brief Returns specified OpenMP runtime function.
404 /// \param Function OpenMP runtime function.
405 /// \return Specified function.
406 llvm::Constant *createRuntimeFunction(unsigned Function);
408 /// \brief Returns __kmpc_for_static_init_* runtime function for the specified
409 /// size \a IVSize and sign \a IVSigned.
410 llvm::Constant *createForStaticInitFunction(unsigned IVSize, bool IVSigned);
412 /// \brief Returns __kmpc_dispatch_init_* runtime function for the specified
413 /// size \a IVSize and sign \a IVSigned.
414 llvm::Constant *createDispatchInitFunction(unsigned IVSize, bool IVSigned);
416 /// \brief Returns __kmpc_dispatch_next_* runtime function for the specified
417 /// size \a IVSize and sign \a IVSigned.
418 llvm::Constant *createDispatchNextFunction(unsigned IVSize, bool IVSigned);
420 /// \brief Returns __kmpc_dispatch_fini_* runtime function for the specified
421 /// size \a IVSize and sign \a IVSigned.
422 llvm::Constant *createDispatchFiniFunction(unsigned IVSize, bool IVSigned);
424 /// \brief If the specified mangled name is not in the module, create and
425 /// return threadprivate cache object. This object is a pointer's worth of
426 /// storage that's reserved for use by the OpenMP runtime.
427 /// \param VD Threadprivate variable.
428 /// \return Cache variable for the specified threadprivate.
429 llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD);
431 /// \brief Emits address of the word in a memory where current thread id is
433 virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc);
435 /// \brief Gets thread id value for the current thread.
437 llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);
439 /// \brief Gets (if variable with the given name already exist) or creates
440 /// internal global variable with the specified Name. The created variable has
441 /// linkage CommonLinkage by default and is initialized by null value.
442 /// \param Ty Type of the global variable. If it is exist already the type
443 /// must be the same.
444 /// \param Name Name of the variable.
445 llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty,
446 const llvm::Twine &Name);
448 /// \brief Set of threadprivate variables with the generated initializer.
449 llvm::SmallPtrSet<const VarDecl *, 4> ThreadPrivateWithDefinition;
451 /// \brief Emits initialization code for the threadprivate variables.
452 /// \param VDAddr Address of the global variable \a VD.
453 /// \param Ctor Pointer to a global init function for \a VD.
454 /// \param CopyCtor Pointer to a global copy function for \a VD.
455 /// \param Dtor Pointer to a global destructor function for \a VD.
456 /// \param Loc Location of threadprivate declaration.
457 void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr,
458 llvm::Value *Ctor, llvm::Value *CopyCtor,
459 llvm::Value *Dtor, SourceLocation Loc);
461 /// \brief Returns corresponding lock object for the specified critical region
462 /// name. If the lock object does not exist it is created, otherwise the
463 /// reference to the existing copy is returned.
464 /// \param CriticalName Name of the critical region.
466 llvm::Value *getCriticalRegionLock(StringRef CriticalName);
468 struct TaskResultTy {
469 llvm::Value *NewTask = nullptr;
470 llvm::Value *TaskEntry = nullptr;
471 llvm::Value *NewTaskNewTaskTTy = nullptr;
473 RecordDecl *KmpTaskTQTyRD = nullptr;
474 llvm::Value *TaskDupFn = nullptr;
476 /// Emit task region for the task directive. The task region is emitted in
478 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
479 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
480 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
482 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
483 /// TaskFunction(gtid, tt->part_id, tt->shareds);
486 /// 2. Copy a list of shared variables to field shareds of the resulting
487 /// structure kmp_task_t returned by the previous call (if any).
488 /// 3. Copy a pointer to destructions function to field destructions of the
489 /// resulting structure kmp_task_t.
490 /// \param D Current task directive.
491 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
492 /// /*part_id*/, captured_struct */*__context*/);
493 /// \param SharedsTy A type which contains references the shared variables.
494 /// \param Shareds Context with the list of shared variables from the \p
496 /// \param Data Additional data for task generation like tiednsee, final
497 /// state, list of privates etc.
498 TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
499 const OMPExecutableDirective &D,
500 llvm::Value *TaskFunction, QualType SharedsTy,
501 Address Shareds, const OMPTaskDataTy &Data);
504 explicit CGOpenMPRuntime(CodeGenModule &CGM);
505 virtual ~CGOpenMPRuntime() {}
506 virtual void clear();
508 /// Emit code for the specified user defined reduction construct.
509 virtual void emitUserDefinedReduction(CodeGenFunction *CGF,
510 const OMPDeclareReductionDecl *D);
511 /// Get combiner/initializer for the specified user-defined reduction, if any.
512 virtual std::pair<llvm::Function *, llvm::Function *>
513 getUserDefinedReduction(const OMPDeclareReductionDecl *D);
514 /// \brief Emits outlined function for the specified OpenMP parallel directive
515 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
516 /// kmp_int32 BoundID, struct context_vars*).
517 /// \param D OpenMP directive.
518 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
519 /// \param InnermostKind Kind of innermost directive (for simple directives it
520 /// is a directive itself, for combined - its innermost directive).
521 /// \param CodeGen Code generation sequence for the \a D directive.
522 virtual llvm::Value *emitParallelOrTeamsOutlinedFunction(
523 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
524 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
526 /// \brief Emits outlined function for the OpenMP task directive \a D. This
527 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
529 /// \param D OpenMP directive.
530 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
531 /// \param PartIDVar Variable for partition id in the current OpenMP untied
533 /// \param TaskTVar Variable for task_t argument.
534 /// \param InnermostKind Kind of innermost directive (for simple directives it
535 /// is a directive itself, for combined - its innermost directive).
536 /// \param CodeGen Code generation sequence for the \a D directive.
537 /// \param Tied true if task is generated for tied task, false otherwise.
538 /// \param NumberOfParts Number of parts in untied task. Ignored for tied
541 virtual llvm::Value *emitTaskOutlinedFunction(
542 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
543 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
544 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
545 bool Tied, unsigned &NumberOfParts);
547 /// \brief Cleans up references to the objects in finished function.
549 void functionFinished(CodeGenFunction &CGF);
551 /// \brief Emits code for parallel or serial call of the \a OutlinedFn with
552 /// variables captured in a record which address is stored in \a
554 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
555 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
556 /// \param CapturedVars A pointer to the record with the references to
557 /// variables used in \a OutlinedFn function.
558 /// \param IfCond Condition in the associated 'if' clause, if it was
559 /// specified, nullptr otherwise.
561 virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
562 llvm::Value *OutlinedFn,
563 ArrayRef<llvm::Value *> CapturedVars,
566 /// \brief Emits a critical region.
567 /// \param CriticalName Name of the critical region.
568 /// \param CriticalOpGen Generator for the statement associated with the given
570 /// \param Hint Value of the 'hint' clause (optional).
571 virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
572 const RegionCodeGenTy &CriticalOpGen,
574 const Expr *Hint = nullptr);
576 /// \brief Emits a master region.
577 /// \param MasterOpGen Generator for the statement associated with the given
579 virtual void emitMasterRegion(CodeGenFunction &CGF,
580 const RegionCodeGenTy &MasterOpGen,
583 /// \brief Emits code for a taskyield directive.
584 virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
586 /// \brief Emit a taskgroup region.
587 /// \param TaskgroupOpGen Generator for the statement associated with the
588 /// given taskgroup region.
589 virtual void emitTaskgroupRegion(CodeGenFunction &CGF,
590 const RegionCodeGenTy &TaskgroupOpGen,
593 /// \brief Emits a single region.
594 /// \param SingleOpGen Generator for the statement associated with the given
596 virtual void emitSingleRegion(CodeGenFunction &CGF,
597 const RegionCodeGenTy &SingleOpGen,
599 ArrayRef<const Expr *> CopyprivateVars,
600 ArrayRef<const Expr *> DestExprs,
601 ArrayRef<const Expr *> SrcExprs,
602 ArrayRef<const Expr *> AssignmentOps);
604 /// \brief Emit an ordered region.
605 /// \param OrderedOpGen Generator for the statement associated with the given
607 virtual void emitOrderedRegion(CodeGenFunction &CGF,
608 const RegionCodeGenTy &OrderedOpGen,
609 SourceLocation Loc, bool IsThreads);
611 /// \brief Emit an implicit/explicit barrier for OpenMP threads.
612 /// \param Kind Directive for which this implicit barrier call must be
613 /// generated. Must be OMPD_barrier for explicit barrier generation.
614 /// \param EmitChecks true if need to emit checks for cancellation barriers.
615 /// \param ForceSimpleCall true simple barrier call must be emitted, false if
616 /// runtime class decides which one to emit (simple or with cancellation
619 virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
620 OpenMPDirectiveKind Kind,
621 bool EmitChecks = true,
622 bool ForceSimpleCall = false);
624 /// \brief Check if the specified \a ScheduleKind is static non-chunked.
625 /// This kind of worksharing directive is emitted without outer loop.
626 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
627 /// \param Chunked True if chunk is specified in the clause.
629 virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
632 /// \brief Check if the specified \a ScheduleKind is static non-chunked.
633 /// This kind of distribute directive is emitted without outer loop.
634 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
635 /// \param Chunked True if chunk is specified in the clause.
637 virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,
640 /// \brief Check if the specified \a ScheduleKind is dynamic.
641 /// This kind of worksharing directive is emitted without outer loop.
642 /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
644 virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;
646 virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
647 const OpenMPScheduleTy &ScheduleKind,
648 unsigned IVSize, bool IVSigned, bool Ordered,
650 llvm::Value *Chunk = nullptr);
652 /// \brief Call the appropriate runtime routine to initialize it before start
655 /// Depending on the loop schedule, it is nesessary to call some runtime
656 /// routine before start of the OpenMP loop to get the loop upper / lower
657 /// bounds \a LB and \a UB and stride \a ST.
659 /// \param CGF Reference to current CodeGenFunction.
660 /// \param Loc Clang source location.
661 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
662 /// \param IVSize Size of the iteration variable in bits.
663 /// \param IVSigned Sign of the interation variable.
664 /// \param Ordered true if loop is ordered, false otherwise.
665 /// \param IL Address of the output variable in which the flag of the
666 /// last iteration is returned.
667 /// \param LB Address of the output variable in which the lower iteration
668 /// number is returned.
669 /// \param UB Address of the output variable in which the upper iteration
670 /// number is returned.
671 /// \param ST Address of the output variable in which the stride value is
672 /// returned nesessary to generated the static_chunked scheduled loop.
673 /// \param Chunk Value of the chunk for the static_chunked scheduled loop.
674 /// For the default (nullptr) value, the chunk 1 will be used.
676 virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
677 const OpenMPScheduleTy &ScheduleKind,
678 unsigned IVSize, bool IVSigned, bool Ordered,
679 Address IL, Address LB, Address UB, Address ST,
680 llvm::Value *Chunk = nullptr);
683 /// \param CGF Reference to current CodeGenFunction.
684 /// \param Loc Clang source location.
685 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
686 /// \param IVSize Size of the iteration variable in bits.
687 /// \param IVSigned Sign of the interation variable.
688 /// \param Ordered true if loop is ordered, false otherwise.
689 /// \param IL Address of the output variable in which the flag of the
690 /// last iteration is returned.
691 /// \param LB Address of the output variable in which the lower iteration
692 /// number is returned.
693 /// \param UB Address of the output variable in which the upper iteration
694 /// number is returned.
695 /// \param ST Address of the output variable in which the stride value is
696 /// returned nesessary to generated the static_chunked scheduled loop.
697 /// \param Chunk Value of the chunk for the static_chunked scheduled loop.
698 /// For the default (nullptr) value, the chunk 1 will be used.
700 virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
701 OpenMPDistScheduleClauseKind SchedKind,
702 unsigned IVSize, bool IVSigned,
703 bool Ordered, Address IL, Address LB,
704 Address UB, Address ST,
705 llvm::Value *Chunk = nullptr);
707 /// \brief Call the appropriate runtime routine to notify that we finished
708 /// iteration of the ordered loop with the dynamic scheduling.
710 /// \param CGF Reference to current CodeGenFunction.
711 /// \param Loc Clang source location.
712 /// \param IVSize Size of the iteration variable in bits.
713 /// \param IVSigned Sign of the interation variable.
715 virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF,
716 SourceLocation Loc, unsigned IVSize,
719 /// \brief Call the appropriate runtime routine to notify that we finished
720 /// all the work with current loop.
722 /// \param CGF Reference to current CodeGenFunction.
723 /// \param Loc Clang source location.
725 virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc);
727 /// Call __kmpc_dispatch_next(
728 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
729 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
730 /// kmp_int[32|64] *p_stride);
731 /// \param IVSize Size of the iteration variable in bits.
732 /// \param IVSigned Sign of the interation variable.
733 /// \param IL Address of the output variable in which the flag of the
734 /// last iteration is returned.
735 /// \param LB Address of the output variable in which the lower iteration
736 /// number is returned.
737 /// \param UB Address of the output variable in which the upper iteration
738 /// number is returned.
739 /// \param ST Address of the output variable in which the stride value is
741 virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
742 unsigned IVSize, bool IVSigned,
743 Address IL, Address LB,
744 Address UB, Address ST);
746 /// \brief Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
747 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
749 /// \param NumThreads An integer value of threads.
750 virtual void emitNumThreadsClause(CodeGenFunction &CGF,
751 llvm::Value *NumThreads,
754 /// \brief Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
755 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
756 virtual void emitProcBindClause(CodeGenFunction &CGF,
757 OpenMPProcBindClauseKind ProcBind,
760 /// \brief Returns address of the threadprivate variable for the current
762 /// \param VD Threadprivate variable.
763 /// \param VDAddr Address of the global variable \a VD.
764 /// \param Loc Location of the reference to threadprivate var.
765 /// \return Address of the threadprivate variable for the current thread.
766 virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
771 /// \brief Emit a code for initialization of threadprivate variable. It emits
772 /// a call to runtime library which adds initial value to the newly created
773 /// threadprivate variable (if it is not constant) and registers destructor
774 /// for the variable (if any).
775 /// \param VD Threadprivate variable.
776 /// \param VDAddr Address of the global variable \a VD.
777 /// \param Loc Location of threadprivate declaration.
778 /// \param PerformInit true if initialization expression is not constant.
779 virtual llvm::Function *
780 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
781 SourceLocation Loc, bool PerformInit,
782 CodeGenFunction *CGF = nullptr);
784 /// \brief Emit flush of the variables specified in 'omp flush' directive.
785 /// \param Vars List of variables to flush.
786 virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
789 /// \brief Emit task region for the task directive. The task region is
790 /// emitted in several steps:
791 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
792 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
793 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
795 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
796 /// TaskFunction(gtid, tt->part_id, tt->shareds);
799 /// 2. Copy a list of shared variables to field shareds of the resulting
800 /// structure kmp_task_t returned by the previous call (if any).
801 /// 3. Copy a pointer to destructions function to field destructions of the
802 /// resulting structure kmp_task_t.
803 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
804 /// kmp_task_t *new_task), where new_task is a resulting structure from
806 /// \param D Current task directive.
807 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
808 /// /*part_id*/, captured_struct */*__context*/);
809 /// \param SharedsTy A type which contains references the shared variables.
810 /// \param Shareds Context with the list of shared variables from the \p
812 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
814 /// \param Data Additional data for task generation like tiednsee, final
815 /// state, list of privates etc.
816 virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
817 const OMPExecutableDirective &D,
818 llvm::Value *TaskFunction, QualType SharedsTy,
819 Address Shareds, const Expr *IfCond,
820 const OMPTaskDataTy &Data);
822 /// Emit task region for the taskloop directive. The taskloop region is
823 /// emitted in several steps:
824 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
825 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
826 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
828 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
829 /// TaskFunction(gtid, tt->part_id, tt->shareds);
832 /// 2. Copy a list of shared variables to field shareds of the resulting
833 /// structure kmp_task_t returned by the previous call (if any).
834 /// 3. Copy a pointer to destructions function to field destructions of the
835 /// resulting structure kmp_task_t.
836 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
837 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
838 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
839 /// is a resulting structure from
841 /// \param D Current task directive.
842 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
843 /// /*part_id*/, captured_struct */*__context*/);
844 /// \param SharedsTy A type which contains references the shared variables.
845 /// \param Shareds Context with the list of shared variables from the \p
847 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
849 /// \param Data Additional data for task generation like tiednsee, final
850 /// state, list of privates etc.
851 virtual void emitTaskLoopCall(
852 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
853 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
854 const Expr *IfCond, const OMPTaskDataTy &Data);
856 /// \brief Emit code for the directive that does not require outlining.
858 /// \param InnermostKind Kind of innermost directive (for simple directives it
859 /// is a directive itself, for combined - its innermost directive).
860 /// \param CodeGen Code generation sequence for the \a D directive.
861 /// \param HasCancel true if region has inner cancel directive, false
863 virtual void emitInlinedDirective(CodeGenFunction &CGF,
864 OpenMPDirectiveKind InnermostKind,
865 const RegionCodeGenTy &CodeGen,
866 bool HasCancel = false);
867 /// \brief Emit a code for reduction clause. Next code should be emitted for
871 /// static kmp_critical_name lock = { 0 };
873 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
875 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
880 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
881 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
882 /// RedList, reduce_func, &<lock>)) {
885 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
887 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
891 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
898 /// \param Privates List of private copies for original reduction arguments.
899 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
900 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
901 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
902 /// or 'operator binop(LHS, RHS)'.
903 /// \param WithNowait true if parent directive has also nowait clause, false
905 virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
906 ArrayRef<const Expr *> Privates,
907 ArrayRef<const Expr *> LHSExprs,
908 ArrayRef<const Expr *> RHSExprs,
909 ArrayRef<const Expr *> ReductionOps,
910 bool WithNowait, bool SimpleReduction);
912 /// \brief Emit code for 'taskwait' directive.
913 virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc);
915 /// \brief Emit code for 'cancellation point' construct.
916 /// \param CancelRegion Region kind for which the cancellation point must be
919 virtual void emitCancellationPointCall(CodeGenFunction &CGF,
921 OpenMPDirectiveKind CancelRegion);
923 /// \brief Emit code for 'cancel' construct.
924 /// \param IfCond Condition in the associated 'if' clause, if it was
925 /// specified, nullptr otherwise.
926 /// \param CancelRegion Region kind for which the cancel must be emitted.
928 virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
930 OpenMPDirectiveKind CancelRegion);
932 /// \brief Emit outilined function for 'target' directive.
933 /// \param D Directive to emit.
934 /// \param ParentName Name of the function that encloses the target region.
935 /// \param OutlinedFn Outlined function value to be defined by this call.
936 /// \param OutlinedFnID Outlined function ID value to be defined by this call.
937 /// \param IsOffloadEntry True if the outlined function is an offload entry.
938 /// \param CodeGen Code generation sequence for the \a D directive.
939 /// An oulined function may not be an entry if, e.g. the if clause always
940 /// evaluates to false.
941 virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
942 StringRef ParentName,
943 llvm::Function *&OutlinedFn,
944 llvm::Constant *&OutlinedFnID,
946 const RegionCodeGenTy &CodeGen);
948 /// \brief Emit the target offloading code associated with \a D. The emitted
949 /// code attempts offloading the execution to the device, an the event of
950 /// a failure it executes the host version outlined in \a OutlinedFn.
951 /// \param D Directive to emit.
952 /// \param OutlinedFn Host version of the code to be offloaded.
953 /// \param OutlinedFnID ID of host version of the code to be offloaded.
954 /// \param IfCond Expression evaluated in if clause associated with the target
955 /// directive, or null if no if clause is used.
956 /// \param Device Expression evaluated in device clause associated with the
957 /// target directive, or null if no device clause is used.
958 /// \param CapturedVars Values captured in the current region.
959 virtual void emitTargetCall(CodeGenFunction &CGF,
960 const OMPExecutableDirective &D,
961 llvm::Value *OutlinedFn,
962 llvm::Value *OutlinedFnID, const Expr *IfCond,
964 ArrayRef<llvm::Value *> CapturedVars);
966 /// \brief Emit the target regions enclosed in \a GD function definition or
967 /// the function itself in case it is a valid device function. Returns true if
968 /// \a GD was dealt with successfully.
969 /// \param GD Function to scan.
970 virtual bool emitTargetFunctions(GlobalDecl GD);
972 /// \brief Emit the global variable if it is a valid device global variable.
973 /// Returns true if \a GD was dealt with successfully.
974 /// \param GD Variable declaration to emit.
975 virtual bool emitTargetGlobalVariable(GlobalDecl GD);
977 /// \brief Emit the global \a GD if it is meaningful for the target. Returns
978 /// if it was emitted succesfully.
979 /// \param GD Global to scan.
980 virtual bool emitTargetGlobal(GlobalDecl GD);
982 /// \brief Creates the offloading descriptor in the event any target region
983 /// was emitted in the current module and return the function that registers
985 virtual llvm::Function *emitRegistrationFunction();
987 /// \brief Emits code for teams call of the \a OutlinedFn with
988 /// variables captured in a record which address is stored in \a
990 /// \param OutlinedFn Outlined function to be run by team masters. Type of
991 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
992 /// \param CapturedVars A pointer to the record with the references to
993 /// variables used in \a OutlinedFn function.
995 virtual void emitTeamsCall(CodeGenFunction &CGF,
996 const OMPExecutableDirective &D,
997 SourceLocation Loc, llvm::Value *OutlinedFn,
998 ArrayRef<llvm::Value *> CapturedVars);
1000 /// \brief Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
1001 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
1002 /// for num_teams clause.
1003 /// \param NumTeams An integer expression of teams.
1004 /// \param ThreadLimit An integer expression of threads.
1005 virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
1006 const Expr *ThreadLimit, SourceLocation Loc);
1008 /// Struct that keeps all the relevant information that should be kept
1009 /// throughout a 'target data' region.
1010 class TargetDataInfo {
1011 /// Set to true if device pointer information have to be obtained.
1012 bool RequiresDevicePointerInfo = false;
1015 /// The array of base pointer passed to the runtime library.
1016 llvm::Value *BasePointersArray = nullptr;
1017 /// The array of section pointers passed to the runtime library.
1018 llvm::Value *PointersArray = nullptr;
1019 /// The array of sizes passed to the runtime library.
1020 llvm::Value *SizesArray = nullptr;
1021 /// The array of map types passed to the runtime library.
1022 llvm::Value *MapTypesArray = nullptr;
1023 /// The total number of pointers passed to the runtime library.
1024 unsigned NumberOfPtrs = 0u;
1025 /// Map between the a declaration of a capture and the corresponding base
1026 /// pointer address where the runtime returns the device pointers.
1027 llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap;
1029 explicit TargetDataInfo() {}
1030 explicit TargetDataInfo(bool RequiresDevicePointerInfo)
1031 : RequiresDevicePointerInfo(RequiresDevicePointerInfo) {}
1032 /// Clear information about the data arrays.
1033 void clearArrayInfo() {
1034 BasePointersArray = nullptr;
1035 PointersArray = nullptr;
1036 SizesArray = nullptr;
1037 MapTypesArray = nullptr;
1040 /// Return true if the current target data information has valid arrays.
1042 return BasePointersArray && PointersArray && SizesArray &&
1043 MapTypesArray && NumberOfPtrs;
1045 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
1048 /// \brief Emit the target data mapping code associated with \a D.
1049 /// \param D Directive to emit.
1050 /// \param IfCond Expression evaluated in if clause associated with the
1051 /// target directive, or null if no device clause is used.
1052 /// \param Device Expression evaluated in device clause associated with the
1053 /// target directive, or null if no device clause is used.
1054 /// \param Info A record used to store information that needs to be preserved
1055 /// until the region is closed.
1056 virtual void emitTargetDataCalls(CodeGenFunction &CGF,
1057 const OMPExecutableDirective &D,
1058 const Expr *IfCond, const Expr *Device,
1059 const RegionCodeGenTy &CodeGen,
1060 TargetDataInfo &Info);
1062 /// \brief Emit the data mapping/movement code associated with the directive
1063 /// \a D that should be of the form 'target [{enter|exit} data | update]'.
1064 /// \param D Directive to emit.
1065 /// \param IfCond Expression evaluated in if clause associated with the target
1066 /// directive, or null if no if clause is used.
1067 /// \param Device Expression evaluated in device clause associated with the
1068 /// target directive, or null if no device clause is used.
1069 virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF,
1070 const OMPExecutableDirective &D,
1072 const Expr *Device);
1074 /// Marks function \a Fn with properly mangled versions of vector functions.
1075 /// \param FD Function marked as 'declare simd'.
1076 /// \param Fn LLVM function that must be marked with 'declare simd'
1078 virtual void emitDeclareSimdFunction(const FunctionDecl *FD,
1079 llvm::Function *Fn);
1081 /// Emit initialization for doacross loop nesting support.
1082 /// \param D Loop-based construct used in doacross nesting construct.
1083 virtual void emitDoacrossInit(CodeGenFunction &CGF,
1084 const OMPLoopDirective &D);
1086 /// Emit code for doacross ordered directive with 'depend' clause.
1087 /// \param C 'depend' clause with 'sink|source' dependency kind.
1088 virtual void emitDoacrossOrdered(CodeGenFunction &CGF,
1089 const OMPDependClause *C);
1092 } // namespace CodeGen
1093 } // namespace clang